Spring Boot--自动配置原理

引言

做为Spring Boot的精髓,自动配置原理的工做过程每每只有在“面试”的时候才能用得上,可是若是在工做中你可以深刻的理解Spring Boot的自动配置原理,将无往不利。面试

Spring Boot的出现,得益于“习惯优于配置”的理念,没有繁琐的配置、难以集成的内容(大多数流行第三方技术都被集成),这是基于Spring 4.x提供的按条件配置Bean的能力。spring

springboot的配置文件 :application.properties 或 application.ymlspringboot

示例:图片那么问题来了:这些配置是如何在Spring Boot项目中生效的呢?那么接下来,就须要聚焦本篇博客的主题:自动配置工做原理或者叫实现方式。app

Spring Boot关于自动配置的源码在spring-boot-autoconfigure-x.x.x.x.jar中:ide

如图:图片Spring Boot的启动类上有一个@SpringBootApplication注解,这个注解是Spring Boot项目必不可少的注解,也是springboot自动配置的核心spring-boot

1.@Configuration的注解类标识这个类可使用Spring IoC容器做为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。this

二、@EnableAutoConfiguration:可以自动配置spring的上下文,试图猜想和配置你想要的bean类,一般会自动根据你的类路径和你的bean定义自动配置。spa

三、@ComponentScan:会自动扫描指定包下的所有标有@Component的类,并注册成bean,固然包括@Component下的子注解@Service,@Repository,@Controller。图片@SpringBootApplication是一个复合注解或派生注解,在@SpringBootApplication中有一个注解@EnableAutoConfiguration,翻译的话就是开启自动配置 @Configuration //表示这是一个配置类,也能够给容器中添加组件图片咱们查看@EnableAutoConfiguration注解 ,会发现他引入了个 类
AutoConfigurationImportSelector.class
图片进入AutoConfigurationImportSelector类中,咱们会发现 有这个方法 如图翻译

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");        return configurations;    }

出现报错 从中咱们能够推出 @EnableAutoConfiguration注解 如何自动装配了 "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct." 翻译:在META-INF/spring.factories中找不到自动配置类。若是使用自定义打包,请确保文件正确无误。orm

在保重咱们找到的了对应的spring.factories 文件图片图片打开以后,这个@EnableAutoConfiguration注解经过@SpringBootApplication被间接的标记在了Spring Boot的启动类上。在SpringApplication.run(...)的内部就会执行selectImports()方法,找到全部JavaConfig自动配置类的全限定名对应的class,而后将全部自动配置类加载到Spring容器中。

相关文章
相关标签/搜索