0
点赞
收藏
分享

微信扫一扫

【SpringBoot学习】@EnableAutoConfiguration 和 @ComponentScan区别示例

王传学 2022-02-19 阅读 50
spring boot

代码地址:

 https://gitee.com/better-code/SpringBoot-Example/springboot01_1/

代码结构:

具体代码使用:

com.example.springboot01_1.web.HelloController

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        String name = "SpringBoot";
        return "Hello "+name+" !";
    }
}

com.example.springboot01_1.App

@EnableAutoConfiguration
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Run App.java
访问 http://localhost:8080/hello,页面报错 Whitelabel Error Page


修改 App.java 如下(增加@ComponentScan

@EnableAutoConfiguration
@ComponentScan
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Run App.java
访问 http://localhost:8080/hello,页面打印 Hello SpringBoot !


修改 App.java 如下(去掉@EnableAutoConfiguration

@ComponentScan
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Run App.java 时,提示错误

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.

总结:

例如,如果你正在编写一个JPA应用,Spring将搜索 @EnableAutoConfiguration 注解的类所在包下的 @Entity 实体。采用root package方式,你就可以使用 @ComponentScan 注解而不需要指定 basePackage 属性,也可以使用 @SpringBootApplication 注解,只要将main类放到root package中。

@ComponentScan + @EnableAutoConfiguration = @SpringBootApplication



参考自,对原文有纠正:https://www.jianshu.com/p/bcd4b0078d2a

举报

相关推荐

ComponentScan注解学习笔记

0 条评论