Spring Boot 正常启动后访问Controller提示404

       问题描述

  今天重新在搭建Spring Boot项目的时候遇到访问Controller报404错误,之前在搭建的时候没怎么注意这块。新创建项目成功后,作为项目启动类的Application在com.blog.start包下面,然后我写了一个Controller,然后包的路径是com.blog.ty.controller用的@RestController 注解去配置的controller,然后路径也搭好了,但是浏览器一直报404。最后找到原因是Spring Boot只会扫描启动类当前包和以下的包 ,就是说现在我启动类的包是在com.blog.start下面,然后他就只会扫描com.blog.start或者com.blog.start.*下面所以的包,所以我的Controller在com.blog.ty.controller包下面Spring Boot就没有扫描到。

  解决办法

  方法一:

    以启动类的包路径作为顶层包路径,列如启动类包为com.blog.start,那么Controller包路径就为com.blog.start.controller。

  方法二:

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

    

1 @SpringBootApplication
2 @ComponentScan(basePackages = {"com.blog.*,com.blog.ty.*"})  //指定扫描包路径
3 public class MyBlogApplication {
4 
5     public static void main(String[] args) {
6         SpringApplication.run(MyBlogApplication.class, args);
7     }
8 }
原文地址:https://www.cnblogs.com/tangyin/p/9517588.html