1. 程式人生 > >springboot啟動後controller訪問404

springboot啟動後controller訪問404

nba 掃描 cat resp rop index start 可能 .repo

  • 首先需要在springboot的啟動類上面使用@SpringBootApplication註解,並且指定掃描的包的位置,如下:

    package com.example;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication(scanBasePackages="com.example.controller")
    public class DemoApplication {

    public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
    }

    }
    這裏如過需要掃描多個包可以這麽寫scanBasePackages={"com.xxx","com.xxx"}這種形式即可

  • 2.其次在當前的pom.xml中指定springboot啟動類:

    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <!-- 這裏是我本人的springboot啟動類位置,請根據自己的情況改動,idea下面可以點出來的-->
    <start-class>com.example.DemoApplication</start-class>
    </properties>
    <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
    <fork>true</fork>
    <mainClass>${start-class}</mainClass>
    </configuration>
    </plugin>
    </plugins>
    </build>

    3.這裏是我的controller:

        package com.example.controller;
    
        import org.springframework.stereotype.Controller;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.ResponseBody;
    
        @Controller
        @RequestMapping("/home")
        public class TestController {
    
                @RequestMapping("/hello")
                @ResponseBody
                public String index(){
                        return "hello world";
                }
        }

    註意:以上的springboot版本是2.0.5.RELEASE版,不同版本可能會有所不同。
    springboot啟動後瀏覽器輸入下面的URL即可
    http://localhost:8080/home/hello

    springboot啟動後controller訪問404