如下图所示,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。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐