springboot中controller无法访问

在springboot中,遇到controller无法访问的问题
springboot中controller无法访问
路径如下:
springboot中controller无法访问
原因:而出现这种情况的原因在于@SpringBootApplication。下图是官方给出的注解使用说明:
@[email protected][email protected][email protected]

@Configuration:该注解将类可以看成配置文件,通常和@Bean配合使用

@EnableAutoConfiguration:在程序启动时自动加载配置

@ComponentScan:会自动扫描指定包下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。

我们需要关注的就是@ComponentScan,下面是官方给出的一段对于@ComponentScan的介绍

将主类放在根目录下,那么只需要配置一个@ComponentScan,无需添加任何参数。而这一句就解释了编写的第一个Controller没有问题:
springboot中controller无法访问
springboot中controller无法访问

而无法被加载,LoginController和主类App不再同一个目录下,无法被自动加载,所以需要我们去手动加载。于是我在主类上手动添加了一条@ComponentScan,将LoginController所在的路径进行添加,如下图所示
springboot中controller无法访问
但是APP下的controller会出现问题:
springboot中controller无法访问
说明自己配置的@ComponentScan覆盖了@SpringBootApplication中的@ComponentScan,但是由于@SpringBootApplication还有另外两个标签,所以在主类中配置的Controller还是好使的,但是在其子包下的配置都不好使了,无法被自动搜索到。

所以在配置@ComponentScan时,推荐以下两种配置,第一种是将根路径作为参数,第二种是多配置几个路径,如下图所示
第一种:
springboot中controller无法访问
参考:
https://www.cnblogs.com/remember-me/p/10091126.html