Spring Boot 自动配置(auto

本章,我们为你揭秘Spring Boot自动配置(Auto Configuration)运行机制,谈到auto-configuration,肯定离不开@EnableAutoConfiguration注解。

1package org.springframework.boot.autoconfigure; 2 3@Target(ElementType.TYPE) 4@Retention(RetentionPolicy.RUNTIME) 5@Documented 6@Inherited 7@AutoConfigurationPackage 8@Import(EnableAutoConfigurationImportSelector.class) 9public @interface EnableAutoConfiguration { 10 11 Class<?>[] exclude() default {}; 12 String[] excludeName() default {}; 13}

这里涉及了两个元注解: @AutoConfigurationPackage, @Import(EnableAutoConfigurationImportSelector.class),其中@AutoConfigurationPackage定义如下:

1package org.springframework.boot.autoconfigure; 2 3import .... 4 5@Target(ElementType.TYPE) 6@Retention(RetentionPolicy.RUNTIME) 7@Documented 8@Inherited 9@Import(AutoConfigurationPackages.Registrar.class) 10public @interface AutoConfigurationPackage { 11 12}

@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)**来获取到这个配置列表,下面是示例代码。

1package com.logicbig.example; 2 3import ... 4 5@EnableAutoConfiguration 6public class AutoConfigurationPackagesTest { 7 8 public static void main (String[] args) { 9 10 SpringApplication app = 11 new SpringApplication(AutoConfigurationPackagesTest.class); 12 app.setBannerMode(Banner.Mode.OFF); 13 app.setLogStartupInfo(false); 14 ConfigurableApplicationContext c = app.run(args); 15 List<String> packages = AutoConfigurationPackages.get(c); 16 System.out.println("packages: "+packages); 17 } 18}

代码输出如下:

12017-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 22017-01-03 10:17:38.155 INFO 10752 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 3packages: [com.logicbig.example] 42017-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 52017-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中加载配置类。

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

从spring.factories中查找键值org.springframework.boot.autoconfigure.EnableAutoConfiguration的值:

spring-boot-autoconfigure默认隐式包含在所有启动程序中

下面其中的一个配置类JmxAutoConfiguration的代码段

1 package org.springframework.boot.autoconfigure.jmx; 2 3 ....... 4 import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 5 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 6 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 7 import org.springframework.boot.autoconfigure.condition.SearchStrategy; 8 ..... 9 10 @Configuration 11 @ConditionalOnClass({ MBeanExporter.class }) 12 @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) 13 public class JmxAutoConfiguration implements 14 EnvironmentAware, BeanFactoryAware { 15 ..... 16 }

@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()**才会返回真,还是上面的代码段:

1 @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", 2 havingValue = "true", matchIfMissing = true)

如果我们应用配置了spring.jmx.enabled=true,那么Spring容器将自动注册JmxAutoConfiguration,matchIfMissing=true表示默认情况下(配置属性未设置)为真。

其他一些条件注解

包‘org.springframework.boot.autoconfigure.condition,所有条件注解均遵循ConditionalOnXyz`命名约定。如果想要开发自定义启动包,你需要了解这些API,对于别的开发人员来说,最好也能了解基本的运行机制。

使用–debug参数

1@EnableAutoConfiguration 2public class DebugModeExample { 3 4 public static void main (String[] args) { 5 //just doing this programmatically for demo 6 String[] appArgs = {"--debug"}; 7 8 SpringApplication app = new SpringApplication(DebugModeExample.class); 9 app.setBannerMode(Banner.Mode.OFF); 10 app.setLogStartupInfo(false); 11 app.run(appArgs); 12 } 13}

输出

12017-01-02 21:15:17.322 DEBUG 5704 --- [ main] o.s.boot.SpringApplication : Loading source class com.logicbig.example.DebugModeExample 22017-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) 32017-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 42017-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 52017-01-02 21:15:18.032 INFO 5704 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 62017-01-02 21:15:18.047 DEBUG 5704 --- [ main] utoConfigurationReportLoggingInitializer : 7 8 9========================= 10AUTO-CONFIGURATION REPORT 11========================= 12 13 14Positive matches: 15----------------- 16 17 GenericCacheConfiguration matched: 18 - Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration automatic cache type (CacheCondition) 19 20 JmxAutoConfiguration matched: 21 - @ConditionalOnClass found required class 'org.springframework.jmx.export.MBeanExporter' (OnClassCondition) 22 - @ConditionalOnProperty (spring.jmx.enabled=true) matched (OnPropertyCondition) 23 24 JmxAutoConfiguration#mbeanExporter matched: 25 - @ConditionalOnMissingBean (types: org.springframework.jmx.export.MBeanExporter; SearchStrategy: current) did not find any beans (OnBeanCondition) 26 27 JmxAutoConfiguration#mbeanServer matched: 28 - @ConditionalOnMissingBean (types: javax.management.MBeanServer; SearchStrategy: all) did not find any beans (OnBeanCondition) 29 30 JmxAutoConfiguration#objectNamingStrategy matched: 31 - @ConditionalOnMissingBean (types: org.springframework.jmx.export.naming.ObjectNamingStrategy; SearchStrategy: current) did not find any beans (OnBeanCondition) 32 33 NoOpCacheConfiguration matched: 34 - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration automatic cache type (CacheCondition) 35 36 PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched: 37 - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) did not find any beans (OnBeanCondition) 38 39 RedisCacheConfiguration matched: 40 - Cache org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration automatic cache type (CacheCondition) 41 42 SimpleCacheConfiguration matched: 43 - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition) 44 45 46Negative matches: 47----------------- 48 49 ActiveMQAutoConfiguration: 50 Did not match: 51 - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition) 52 53 AopAutoConfiguration: 54 Did not match: 55 - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition) 56 57 ArtemisAutoConfiguration: 58 Did not match: 59 - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.artemis.jms.client 60 61 ............................... 62 .................... 63 64 65Exclusions: 66----------- 67 68 None 69 70 71Unconditional classes: 72---------------------- 73 74 org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration 75 76 org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration 77 78 org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration 79 80 org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration 81 82 83 842017-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 852017-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

1@EnableAutoConfiguration(exclude = {JmxAutoConfiguration.class}) 2public class ExcludeConfigExample { 3 4 public static void main (String[] args) { 5 //just doing this programmatically for demo 6 String[] appArgs = {"--debug"}; 7 8 SpringApplication app = new SpringApplication(ExcludeConfigExample.class); 9 app.setBannerMode(Banner.Mode.OFF); 10 app.setLogStartupInfo(false); 11 app.run(appArgs); 12 } 13}

输出

1 ............. 2 3========================= 4AUTO-CONFIGURATION REPORT 5========================= 6 7 8Positive matches: 9----------------- 10 11 GenericCacheConfiguration matched: 12 - Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration automatic cache type (CacheCondition) 13 14 NoOpCacheConfiguration matched: 15 - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration automatic cache type (CacheCondition) 16 17 PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched: 18 - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) did not find any beans (OnBeanCondition) 19 20 RedisCacheConfiguration matched: 21 - Cache org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration automatic cache type (CacheCondition) 22 23 SimpleCacheConfiguration matched: 24 - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition) 25 26 27Negative matches: 28----------------- 29 30 ActiveMQAutoConfiguration: 31 Did not match: 32 - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition) 33 34 AopAutoConfiguration: 35 Did not match: 36 - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition) 37 38 39 ................................. 40 41Exclusions: 42----------- 43 44 org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration 45 46 47Unconditional classes: 48---------------------- 49 50 org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration 51 52 org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration 53 54 org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration 55 56 org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )