@EnableAutoConfiguration注解
其实SpringBoot自动配置的原理主要是用的这个@EnableAutoConfiguration注解,其原理为以下三点:
(1)在@EnableAutoConfiguration注解内部使用@Import(AutoConfigurationImportSelector.class)来加载配置类;
(2)配置文件位置:META-INF/spring.factories,该配置文件中定义了大量的配置类,当SpringBoot项目启动时,会自动加载这些配置类,初始化Bean;
(3)并不是所有的Bean都会被初始化,在配置类文件中使用Condition来加载满足条件的Bean。
一个简单的案例
上面的原理看上去还是不太好理解的,这个需要查看源码结合理解,接下来我就就一个简单的例子来解释一下。
一个简单的需求:让SpringBoot自动帮我们创建一个User和Role的Bean对象。
第一步,自定义配置类
- package cs.yangtze.springboot_enable_other.config;
- import cs.yangtze.springboot_enable_other.entity.Role;
- import cs.yangtze.springboot_enable_other.entity.User;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- @Configuration
- public class UserConfig {
- @Bean
- @ConditionalOnProperty(name = "lxr",havingValue = "20")
- public User user(){
- return new User();
- }
- @Bean
- public Role role(){
- return new Role();
- }
- }
第二步,ImportSelector实现类来加载自定义的配置类,这就对应原理的(1)
- package cs.yangtze.springboot_enable_other.config;
- import org.springframework.context.annotation.ImportSelector;
- import org.springframework.core.type.AnnotationMetadata;
- public class MyImportSelect implements ImportSelector {
- @Override
- public String[] selectImports(AnnotationMetadata importingClassMetadata) {
- {"cs.yangtze.springboot_enable_other.config.UserConfig"};
- }
- }
原理(2)中配置文件位置是这样的,但我们自己自定义的配置文件位置不一样,当SpringBoot项目启动时,会自动加载配置类,初始化Bean
- @Import(MyImportSelect.class)
- @SpringBootApplication
- public class SpringbootEnableApplication {
- public static void main(String[] args) {
- ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);
- Role role =context.getBean(Role.class);
- System.out.println(role);
- User user = context.getBean(User.class);
- System.out.println(user);
- }
- }
这时候我们来看一下控制台打印结果:

我们会发现,Role的Bean对象正常打印了,但是User的并没有,这是为什么?
这时候就对应原理(3),并不是所有的Bean都会被初始化,因为我在自定义的UserConfig配置类中,在User上加上了@ConditionalOnProperty(name = “lxr”,havingValue = “20”)条件注解,只有当我的配置文件application.properties中有这个键值对时才能够创建User对象。

最终也是得到正确结果
总结
SpringBoot自动配置的原理就是以上三点,我举的例子应该能够很好地帮助你理解,如果有什么不对的地方还请大家批评指正,这也是我看了几遍视频后的理解。
到此这篇关于SpringBoot使用@EnableAutoConfiguration实现自动配置详解的文章就介绍到这了,更多相关SpringBoot @EnableAutoConfiguration内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!