springboot 项目启动  访问controller 404_springboot

代码写的没有问题呀,为什么访问死活就是404!

//java项目www.fhadmin.org
@Controller
@RequestMapping("/hello")
public class HelloControllerTest {

    @RequestMapping("/index")
    @ResponseBody
    public String index(){
        return "Hello World";
    }

}

springboot 项目启动  访问controller 404_springboot_02


解决方案


错不在代码,而是controller包的位置

新创建项目成功后,作为项目启动类的Application在pers.peng.demo包下面,然后我写了一个Controller,然后包的路径是pers.peng.controller,然后路径也搭好了,但是浏览器一直报404。最后找到原因是Spring Boot只会扫描启动类当前包和以下的包 。就是说现在我启动类的包是在pers.peng.demo下面,然后他就只会扫描pers.peng.demo或者pers.peng.demo.*下面所以的包,所以我的Controller在pers.peng.controller包下面Spring Boot就没有扫描到。
springboot 项目启动  访问controller 404_springboot_03

所以我把demo包删了,把启动类放在了pers.peng下,与包controller同级,如图
springboot 项目启动  访问controller 404_springboot_04
这样问题就解决了。springboot 项目启动  访问controller 404_springboot_05

方法二

在启动上方添加@ComponentScan注解,此注解为指定扫描路径,例如:@ComponentScan(basePackages = {“pers.peng.*”}) 多个不同的以逗号分割。

//java项目www.fhadmin.org
@SpringBootApplication
@ComponentScan(basePackages = {"pers.peng.*"})  //指定扫描包路径
public class MyBlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyBlogApplication.class, args);
    }
}