如下图所示,springboot项目结构如下:

其中主类为DemoApplication,controller放在 com.example.controller下面
TestCtr 代码如下:
@RestController
public class TestCtr {
@GetMapping("/test")
public String test(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("test %s!", name);
}
}
启动springBoot后,通过localhost:8080/test 无法访问到该controller类,原因是由于,springboot中的自动配置,将启动类作为了自动扫描的路径。因此我们需要自己自定包自动扫描的路径到上级目录。
通过在主类 中添加配置:
@SpringBootApplication(scanBasePackages = "com.example")
再次重新启动,即可访问
或者,我们点击进入@SpringBootApplication 注解的实现类,复制实现类里面的合成注解,通过@ComponentScan指定包扫描路劲,如下:
//@SpringBootApplication(scanBasePackages = "com.example")
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.example")
@RestController
重新启动springBoot,同样可以访问该controller。
本文详细阐述了如何在SpringBoot项目中调整扫描路径,以便访问位于com.example.controller的控制器类。通过修改启动类配置或使用@ComponentScan注解,解决了自动扫描默认路径的问题,使localhost:8080/test能够正常访问。
511

被折叠的 条评论
为什么被折叠?



