Spring Boot 自动配置(auto-configurtion) 揭秘
本章,我们为你揭秘Spring Boot自动配置(Auto Configuration)运行机制,谈到auto-configuration,肯定离不开@EnableAutoConfiguration注解。
package org.springframework.boot.autoconfigure; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(EnableAutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { Class<?>[] exclude() default {}; String[] excludeName() default {}; }
这里涉及了两个元注解: @AutoConfigurationPackage, @Import(EnableAutoConfigurationImportSelector.class),其中@AutoConfigurationPackage定义如下:
package org.springframework.boot.autoconfigure; import .... @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(AutoConfigurationPackages.Registrar.class) public @interface AutoConfigurationPackage { }
@AutoConfigurationPackage注解定义中使用了@Import元注解,注解属性value取值为AutoConfigurationPackages.Registrar.class,AutoConfigurationPackages.Registrar类实现了接口ImportBeanDefinitionRegistrar
@Import注解可以接受以下几种定义类型的Java类
- 使用@Configuration注解的类
- ImportSelector实现类:以代码方式处理@Configuration注解类
- DeferredImportSelector实现类:与ImportSelector类似,区别在于处理操作被延迟到所有其他配置项都处理完毕再进行。
- ImportBeanDefinitionRegistrar实现类
AutoConfigurationPackages.Registrar会向Spring容器注册Bean,Bean本身会存储用户自定义配置包列表。Spring Boot 本身会使用这个列表。例如:对于spring-boot-autoconfigure数据访问配置类,可以通过静态方法:AutoConfigurationPackages.get(BeanFactory)来获取到这个配置列表,下面是示例代码。
package com.logicbig.example; import ... @EnableAutoConfiguration public class AutoConfigurationPackagesTest { public static void main (String[] args) { SpringApplication app = new SpringApplication(AutoConfigurationPackagesTest.class); app.setBannerMode(Banner.Mode.OFF); app.setLogStartupInfo(false); ConfigurableApplicationContext c = app.run(args); List<String> packages = AutoConfigurationPackages.get(c); System.out.println("packages: "+packages); } }
代码输出如下:
2017-01-03 10:17:37.372 INFO 10752 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@67b467e9: startup date [Tue Jan 03 10:17:37 CST 2017]; root of context hierarchy 2017-01-03 10:17:38.155 INFO 10752 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup packages: [com.logicbig.example] 2017-01-03 10:17:38.170 INFO 10752 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@67b467e9: startup date [Tue Jan 03 10:17:37 CST 2017]; root of context hierarchy 2017-01-03 10:17:38.171 INFO 10752 --- [ Thread-1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
@Import(EnableAutoConfigurationImportSelector.class)注解是auto-configuration 机制的启动入口。EnableAutoConfigurationImportSelector实现了接口DeferredImportSelector,其内部调用了SpringFactoriesLoader.loadFactoryNames()方法,方法会从META-INF/spring.factories中加载配置类。
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), 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; }
从spring.factories中查找键值org.springframework.boot.autoconfigure.EnableAutoConfiguration的值:
spring-boot-autoconfigure默认隐式包含在所有启动程序中
下面其中的一个配置类JmxAutoConfiguration的代码段
package org.springframework.boot.autoconfigure.jmx; ....... import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.SearchStrategy; ..... @Configuration @ConditionalOnClass({ MBeanExporter.class }) @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) public class JmxAutoConfiguration implements EnvironmentAware, BeanFactoryAware { ..... }
@ConditionalOnClass
@ConditionalOnClass是由元注解@Conditional(OnClassCondition.class定义的注解,我们知道,@Conditional是条件注解,只有条件为真时,@Conditional注解的类、方法才会被加载到Spring组件容器中。对于上面的实例代码段,只有当MBeanExporter.class已经包含在classpath中(具体校验类似于Class.forName的加载逻辑,当目标类包含在classpath中,方法返回为true,否则返回false),OnClassCondition#matches()才会返回为true。
@ConditionalOnProperty
与@ConditionalOnClass类似,@ConditionalOnProperty是另一个@Conditional类型变量,是由元注解@Conditional(OnPropertyCondition.class)所定义的注解。只有当目标属性包含了指定值,OnPropertyCondition#matches()才会返回真,还是上面的代码段:
@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true)
如果我们应用配置了spring.jmx.enabled=true,那么Spring容器将自动注册JmxAutoConfiguration,matchIfMissing=true表示默认情况下(配置属性未设置)为真。
其他一些条件注解
包‘org.springframework.boot.autoconfigure.condition,所有条件注解均遵循ConditionalOnXyz`命名约定。如果想要开发自定义启动包,你需要了解这些API,对于别的开发人员来说,最好也能了解基本的运行机制。
使用–debug参数
@EnableAutoConfiguration public class DebugModeExample { public static void main (String[] args) { //just doing this programmatically for demo String[] appArgs = {"--debug"}; SpringApplication app = new SpringApplication(DebugModeExample.class); app.setBannerMode(Banner.Mode.OFF); app.setLogStartupInfo(false); app.run(appArgs); } }
输出
2017-01-02 21:15:17.322 DEBUG 5704 --- [ main] o.s.boot.SpringApplication : Loading source class com.logicbig.example.DebugModeExample 2017-01-02 21:15:17.379 DEBUG 5704 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped (empty) config file 'file:/D:/LogicBig/example-projects/spring-boot/boot-customizing-autoconfig/target/classes/application.properties' (classpath:/application.properties) 2017-01-02 21:15:17.379 DEBUG 5704 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped (empty) config file 'file:/D:/LogicBig/example-projects/spring-boot/boot-customizing-autoconfig/target/classes/application.properties' (classpath:/application.properties) for profile default 2017-01-02 21:15:17.384 INFO 5704 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f0a87b3: startup date [Mon Jan 02 21:15:17 CST 2017]; root of context hierarchy 2017-01-02 21:15:18.032 INFO 5704 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-01-02 21:15:18.047 DEBUG 5704 --- [ main] utoConfigurationReportLoggingInitializer : ========================= AUTO-CONFIGURATION REPORT ========================= Positive matches: ----------------- GenericCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration automatic cache type (CacheCondition) JmxAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.jmx.export.MBeanExporter' (OnClassCondition) - @ConditionalOnProperty (spring.jmx.enabled=true) matched (OnPropertyCondition) JmxAutoConfiguration#mbeanExporter matched: - @ConditionalOnMissingBean (types: org.springframework.jmx.export.MBeanExporter; SearchStrategy: current) did not find any beans (OnBeanCondition) JmxAutoConfiguration#mbeanServer matched: - @ConditionalOnMissingBean (types: javax.management.MBeanServer; SearchStrategy: all) did not find any beans (OnBeanCondition) JmxAutoConfiguration#objectNamingStrategy matched: - @ConditionalOnMissingBean (types: org.springframework.jmx.export.naming.ObjectNamingStrategy; SearchStrategy: current) did not find any beans (OnBeanCondition) NoOpCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration automatic cache type (CacheCondition) PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched: - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) did not find any beans (OnBeanCondition) RedisCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration automatic cache type (CacheCondition) SimpleCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition) Negative matches: ----------------- ActiveMQAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition) AopAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition) ArtemisAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.artemis.jms.client ............................... .................... Exclusions: ----------- None Unconditional classes: ---------------------- org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration 2017-01-02 21:15:18.058 INFO 5704 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f0a87b3: startup date [Mon Jan 02 21:15:17 CST 2017]; root of context hierarchy 2017-01-02 21:15:18.059 INFO 5704 --- [ Thread-1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
在上面的输出中
- Positive matches:@Conditional条件为真,配置类被Spring容器加载。
- Negative matches: @Conditional条件为假,配置类未被Spring容器加载。
- Exclusions: 应用端明确排除加载配置
- Unconditional classes: 自动配置类不包含任何类级别的条件,也就是说,类始终会被自动加载。
禁止特定类的auto-configuration
@EnableAutoConfiguration(exclude = {JmxAutoConfiguration.class}) public class ExcludeConfigExample { public static void main (String[] args) { //just doing this programmatically for demo String[] appArgs = {"--debug"}; SpringApplication app = new SpringApplication(ExcludeConfigExample.class); app.setBannerMode(Banner.Mode.OFF); app.setLogStartupInfo(false); app.run(appArgs); } }
输出
............. ========================= AUTO-CONFIGURATION REPORT ========================= Positive matches: ----------------- GenericCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration automatic cache type (CacheCondition) NoOpCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration automatic cache type (CacheCondition) PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched: - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) did not find any beans (OnBeanCondition) RedisCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration automatic cache type (CacheCondition) SimpleCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition) Negative matches: ----------------- ActiveMQAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition) AopAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition) ................................. Exclusions: ----------- org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration Unconditional classes: ---------------------- org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
分布式事务中的三种解决方案详解
[TOC] 一、分布式事务前奏 事务:事务是由一组操作构成的可靠的独立的工作单元,事务具备ACID的特性,即原子性、一致性、隔离性和持久性。 本地事务:当事务由资源管理器本地管理时被称作本地事务。本地事务的优点就是支持严格的ACID特性,高效,可靠,状态可以只在资源管理器中维护,而且应用编程模型简单。但是本地事务不具备分布式事务的处理能力,隔离的最小单位受限于资源管理器。 全局事务:当事务由全局事务管理器进行全局管理时成为全局事务,事务管理器负责管理全局的事务状态和参与的资源,协同资源的一致提交回滚。 TX协议:应用或者应用服务器与事务管理器的接口。 XA协议:全局事务管理器与资源管理器的接口。XA是由X/Open组织提出的分布式事务规范。该规范主要定义了全局事务管理器和局部资源管理器之间的接口。主流的数据库产品都实现了XA接口。XA接口是一个双向的系统接口,在事务管理器以及多个资源管理器之间作为通信桥梁。之所以需要XA是因为在分布式系统中从理论上讲两台机器是无法达到一致性状态的,因此引入一个单点进行协调。由全局事务管理器管理和协调的事务可以跨越多个资源和进程。全局事务管理器一般使用X...
- 下一篇
GlusterFS分布式文件系统的卷类型及配置详解
博文大纲:(一)GlusterFS相关概念。(二)GlusterFS各种卷类型的部署及客户端挂载使用。(三)GlusterFS维护命令。 (一)GlusterFS相关概念: GlusterFS是一个开源的分布式文件系统,同时也是Scale-Out存储解决方案Gluster的核心,在存储数据方面有强大的横向扩展能力。GlusterFS主要由存储服务器、客户端及NFS/Samba存储网关(可选组件)组成。GlusterFS架构中最大的设计特点是没有元数据服务器组件,也就是说没有主/从服务器之分,每一个节点都可以是主服务器。 1)Gluster相关参考文档如下(我下面的配置是基于本地yum配置的,若需要搭建最新版本,可直接按照下面的文档链接进行配置): Gluster官网 ,基于centos7/Redhat安装Gluster官方文档 2) GlusterFS相关术语: Brick(存储块):指可信主机池中由主机提供的用于物理存储的专用分区。 Volume(逻辑卷):一个逻辑卷是一组Brick的集合。卷是数据存储的逻辑设备。 FUSE:是一个内核模块,允许用户自己创建文件系统,无须修改内核代码...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- SpringBoot2全家桶,快速入门学习开发网站教程
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- Windows10,CentOS7,CentOS8安装Nodejs环境
- Hadoop3单机部署,实现最简伪集群
- Eclipse初始化配置,告别卡顿、闪退、编译时间过长
- 设置Eclipse缩进为4个空格,增强代码规范
- CentOS7编译安装Gcc9.2.0,解决mysql等软件编译问题
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- Docker安装Oracle12C,快速搭建Oracle学习环境