1. Spring Boot自动配置原理

Spring Boot的自动配置注解是@EnableAutoConfiguration, 从上面的@Import的类可以找到下面自动加载自动配置的映射。

  1. org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames(Class<?>, ClassLoader)
  1. public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
  2.     String factoryClassName = factoryClass.getName();
  3.     try {
  4.         Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
  5.                 lassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
  6.         List<String> result = new ArrayList<String>();
  7.         while (urls.hasMoreElements()) {
  8.             URL url = urls.nextElement();
  9.             Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
  10.            String factoryClassNames = properties.getProperty(factoryClassName);
  11.            result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
  12.        }
  13.        return result;
  14.    }
  15.    catch (IOException ex) {
  16.        throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
  17.                "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
  18.    }
  19. }

这个方法会加载类路径及所有jar包下META-INF/spring.factories配置中映射的自动配置的类。

  1. /**
  2.  * The location to look for factories.
  3.  * <p>Can be present in multiple JAR files.
  4.  */
  5. public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

查看Spring Boot自带的自动配置的包: spring-boot-autoconfigure-1.5.6.RELEASE.jar,打开其中的META-INF/spring.factories文件会找到自动配置的映射。

  1. # Auto Configure
  2. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  3. org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
  4. org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
  5. org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
  6. org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
  7. org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
  8. org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
  9. org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
  10. ...

再来看看数据源自动配置的实现注解

  1. @Configuration
  2. @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
  3. @EnableConfigurationProperties(DataSourceProperties.class)
  4. @Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class })
  5. public class DataSourceAutoConfiguration {
  6. ...

@Configuration,@ConditionalOnClass就是自动配置的核心,首先它得是一个配置文件,其次根据类路径下是否有这个类去自动配置。

      1. 自动配置实战

添加配置类:

  1. import org.slf4j.Logger;
  2. import org.springframework.context.EnvironmentAware;
  3. import org.springframework.core.env.Environment;
  4. import com.oceanpayment.common.utils.logger.LoggerUtils;
  5. public class EnvConfig implements EnvironmentAware {
  6. private final Logger logger = LoggerUtils.getLogger(this);
  7. private Environment env;
  8. public String getStringValue(String key) {
  9. return env.getProperty(key);
  10. }
  11. public Long getLongValue(String key) {
  12. String value = getStringValue(key);
  13. try {
  14. return Long.parseLong(value);
  15. } catch (Exception e) {
  16. logger.error("字符串转换Long失败:{} = {}", key, value);
  17. }
  18. return 0L;
  19. }
  20. public int getIntValue(String key) {
  21. return getLongValue(key).intValue();
  22. }
  23. @Override
  24. public void setEnvironment(Environment environment) {
  25. this.env = environment;
  26. }
  27. }

添加自动配置类:

  1. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.core.env.PropertyResolver;
  5. @Configuration
  6. @ConditionalOnClass(PropertyResolver.class)
  7. public class EnvAutoConfig {
  8. @Bean
  9. public EnvConfig envConfig() {
  10. return new EnvConfig();
  11. }
  12. }

创建META-INF/spring.factories文件,添加自动配置映射:

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\
  2. com.oceanpayment.common.config.env.EnvAutoConfig

这样就搞定了。

      1. 查看自动配置报告

怎么查看自己加的自动配置类有没有被加载,或者查看所有自动配置激活的和未激活的可以通过以下几种试查看。

  • spring-boot:run运行的在对话框Enviroment中加入debug=true变量
  • java -jar xx.jar --debug
  • main方法运行,在VM Argumanets加入-Ddebug
  • 直接在application文件中加入debug=true

如果集成了spring-boot-starter-actuator监控,通过autoconfig端点也可以查看。

启动后会在控制台看到以下自动配置报告信息:

  1. =========================
  2. AUTO-CONFIGURATION REPORT
  3. =========================
  4. Positive matches:
  5. -----------------
  6. AopAutoConfiguration matched:
  7. - @ConditionalOnClass found required classes 'org.springframework.context.annotation.EnableAspectJAutoProxy', 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  8. - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)
  9. ...
  10. EnvAutoConfig matched:
  11. - @ConditionalOnClass found required class 'org.springframework.core.env.PropertyResolver'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  12. ErrorMvcAutoConfiguration matched:
  13. - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  14. - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)
  15. ErrorMvcAutoConfiguration#basicErrorController matched:
  16. - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.ErrorController; SearchStrategy: current) did not find any beans (OnBeanCondition)
  17. ...
  18. Negative matches:
  19. -----------------
  20. ActiveMQAutoConfiguration:
  21. Did not match:
  22. - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
  23. AopAutoConfiguration.JdkDynamicAutoProxyConfiguration:
  24. Did not match:
  25. - @ConditionalOnProperty (spring.aop.proxy-target-class=false) found different value in property 'proxy-target-class' (OnPropertyCondition)
  26. ArtemisAutoConfiguration:
  27. Did not match:
  28. - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory' (OnClassCondition)
  29. BatchAutoConfiguration:
  30. Did not match:
  31. - @ConditionalOnClass did not find required class 'org.springframework.batch.core.launch.JobLauncher' (OnClassCondition)
  32. ...

Positive matches:已经启用的自动配置

Negative matches:未启用的自动配置

从报告中看到自己添加的EnvAutoConfig已经自动配置了。

      1. Auto-configuration

Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.

You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotations to one of your @Configuration classes.

 

You should only ever add one @SpringBootApplication or @EnableAutoConfiguration annotation. We generally recommend that you add one or the other to your primary @Configuration class only.

16.1 Gradually Replacing Auto-configuration

Auto-configuration is non-invasive. At any point, you can start to define your own configuration to replace specific parts of the auto-configuration. For example, if you add your own DataSource bean, the default embedded database support backs away.

If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug switch. Doing so enables debug logs for a selection of core loggers and logs a conditions report to the console.

16.2 Disabling Specific Auto-configuration Classes

If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of @EnableAutoConfiguration to disable them, as shown in the following example:

import org.springframework.boot.autoconfigure.*;

import org.springframework.boot.autoconfigure.jdbc.*;

import org.springframework.context.annotation.*;

@Configuration

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

public class MyConfiguration {

}

If the class is not on the classpath, you can use the excludeName attribute of the annotation and specify the fully qualified name instead. Finally, you can also control the list of auto-configuration classes to exclude by using the spring.autoconfigure.exclude property.

 

You can define exclusions both at the annotation level and by using the property.

Spring Boot自动配置的更多相关文章

  1. Springboot 系列(三)Spring Boot 自动配置原理

    注意:本 Spring Boot 系列文章基于 Spring Boot 版本 v2.1.1.RELEASE 进行学习分析,版本不同可能会有细微差别. 前言 关于配置文件可以配置的内容,在 Spring ...

  2. Spring Boot自动配置与Spring 条件化配置

    SpringBoot自动配置 SpringBoot的自动配置是一个运行时(应用程序启动时)的过程,简化开发时间,无需浪费时间讨论具体的Spring配置,只需考虑如何利用SpringBoot的自动配置即 ...

  3. Spring Boot自动配置原理、实战

    Spring Boot自动配置原理 Spring Boot的自动配置注解是@EnableAutoConfiguration, 从上面的@Import的类可以找到下面自动加载自动配置的映射. org.s ...

  4. Spring boot 自动配置自定义配置文件

    示例如下: 1.   新建 Maven 项目 properties 2.   pom.xml <project xmlns="http://maven.apache.org/POM/4 ...

  5. Spring Boot自动配置原理与实践(一)

    前言 Spring Boot众所周知是为了简化Spring的配置,省去XML的复杂化配置(虽然Spring官方推荐也使用Java配置)采用Java+Annotation方式配置.如下几个问题是我刚开始 ...

  6. Spring Boot自动配置原理(转)

    第3章 Spring Boot自动配置原理 3.1 SpringBoot的核心组件模块 首先,我们来简单统计一下SpringBoot核心工程的源码java文件数量: 我们cd到spring-boot- ...

  7. Spring Boot自动配置如何工作

    通过使用Mongo和MySQL DB实现的示例,深入了解Spring Boot的@Conditional注释世界. 在我以前的文章“为什么选择Spring Boot?”中,我们讨论了如何创建Sprin ...

  8. Spring boot --- 自动配置

    spring boot 自动配置 指的是针对很多spring 应用程序常见的应用功能,spring boot 能自动提供相关配置. spring boot 自动配置加载     Spring boot ...

  9. 使用@AutoConfigureBefore、After、Order调整Spring Boot自动配置顺序

    前言 Spring Boot是Spring家族具有划时代意义的一款产品,它发展自Spring Framework却又高于它,这种高于主要表现在其最重要的三大特性,而相较于这三大特性中更为重要的便是Sp ...

随机推荐

  1. 114. Flatten Binary Tree to Linked List -- 将二叉树转成链表(in-place单枝树)

    Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / \ 2 5 / \ \ 3 4 6 T ...

  2. JavaScript学习总结(二十一)——使用JavaScript的数组实现数据结构中的队列与堆栈

    今天在项目中要使用JavaScript实现数据结构中的队列和堆栈,这里做一下总结. 一.队列和堆栈的简单介绍 1.1.队列的基本概念 队列:是一种支持先进先出(FIFO)的集合,即先被插入的数据,先被 ...

  3. CF 160D Edges in MST 最小生成树的性质,寻桥,缩点,批量处理 难度:3

    http://codeforces.com/problemset/problem/160/D 这道题要求哪条边存在于某个最小生成树中,哪条边不存在于最小生成树中,哪条边绝对存在于最小生成树中 明显桥边 ...

  4. jQuery实现鼠标划过展示大图的方法

    这篇文章主要介绍了jQuery实现鼠标划过展示大图的方法,实例分析了jQuery操作鼠标事件及图片处理的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 本文实例讲述了jQuery实现鼠标划过展示大图 ...

  5. linux下部署tomcat服务器之安装tomcat

    下载tomcat压缩包 apache-tomcat-7.0.82.tar.gz 在把包放到linux 的softwore文件夹下  自己选择文件夹 tar -zxvf apache-tomcat-7. ...

  6. 解析xml(当节点中有多个子节点)

    概要:解析一个xml,当一个节点中又包含多个子节点如何解析,对比一个节点中不包括其他节点的情况. 一,xml样例 <cisReports batNo="查询批次号" unit ...

  7. window.onload 和 body.onload 相互覆盖的本质

    从根源上讲,window.onload和<body onload="alert('test');"> 所绑定的对象都是window ,body是没有onload事件的, ...

  8. 关于VC中LineDDA函数的调用

    在项目里碰到这个函数,不知道怎么使用,记录在这里. 该函数的原型如下: BOOL LineDDA(int nXStart, int nYStart, int nXEnd, int nYEnd, LIN ...

  9. Mysql基本操作(远程登陆,启动,停止,重启,授权)

    1.查看mysql版本 方法一:status; 方法二:select version(); 2.Mysql启动.停止.重启常用命令 a.启动方式 1.使用 service 启动: [root@loca ...

  10. 白帽子讲web安全——白帽子兵法(设计安全方案中的技巧)

    1.Secure By Default原则 白名单:筛选出被允许的,屏蔽其他. 黑名单:屏蔽可能造成的威胁. 2.XSS和SSH XSS攻击:跨站脚本(cross site script)攻击是指恶意 ...