Spring Boot自动配置
- Spring Boot自动配置原理
Spring Boot的自动配置注解是@EnableAutoConfiguration, 从上面的@Import的类可以找到下面自动加载自动配置的映射。
org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames(Class<?>,ClassLoader)
publicstaticList<String> loadFactoryNames(Class<?> factoryClass,ClassLoaderclassLoader) {StringfactoryClassName = factoryClass.getName();try{Enumeration<URL> urls = (classLoader !=null? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :lassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));List<String> result =newArrayList<String>();while(urls.hasMoreElements()) {URL url = urls.nextElement();Propertiesproperties =PropertiesLoaderUtils.loadProperties(newUrlResource(url));StringfactoryClassNames = properties.getProperty(factoryClassName);result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));}returnresult;}catch(IOExceptionex) {thrownewIllegalArgumentException("Unable to load ["+ factoryClass.getName() +"] factories from location ["+ FACTORIES_RESOURCE_LOCATION +"]", ex);}}
这个方法会加载类路径及所有jar包下META-INF/spring.factories配置中映射的自动配置的类。
/*** The location to look for factories.* <p>Can be present in multiple JAR files.*/publicstaticfinalStringFACTORIES_RESOURCE_LOCATION ="META-INF/spring.factories";
查看Spring Boot自带的自动配置的包: spring-boot-autoconfigure-1.5.6.RELEASE.jar,打开其中的META-INF/spring.factories文件会找到自动配置的映射。
# Auto Configureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\...
再来看看数据源自动配置的实现注解
@Configuration@ConditionalOnClass({DataSource.class,EmbeddedDatabaseType.class})@EnableConfigurationProperties(DataSourceProperties.class)@Import({Registrar.class,DataSourcePoolMetadataProvidersConfiguration.class})publicclassDataSourceAutoConfiguration{...
@Configuration,@ConditionalOnClass就是自动配置的核心,首先它得是一个配置文件,其次根据类路径下是否有这个类去自动配置。
- 自动配置实战
添加配置类:
- import org.slf4j.Logger;
- import org.springframework.context.EnvironmentAware;
- import org.springframework.core.env.Environment;
- import com.oceanpayment.common.utils.logger.LoggerUtils;
- public class EnvConfig implements EnvironmentAware {
- private final Logger logger = LoggerUtils.getLogger(this);
- private Environment env;
- public String getStringValue(String key) {
- return env.getProperty(key);
- }
- public Long getLongValue(String key) {
- String value = getStringValue(key);
- try {
- return Long.parseLong(value);
- } catch (Exception e) {
- logger.error("字符串转换Long失败:{} = {}", key, value);
- }
- return 0L;
- }
- public int getIntValue(String key) {
- return getLongValue(key).intValue();
- }
- @Override
- public void setEnvironment(Environment environment) {
- this.env = environment;
- }
- }
添加自动配置类:
- import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.core.env.PropertyResolver;
- @Configuration
- @ConditionalOnClass(PropertyResolver.class)
- public class EnvAutoConfig {
- @Bean
- public EnvConfig envConfig() {
- return new EnvConfig();
- }
- }
创建META-INF/spring.factories文件,添加自动配置映射:
- org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\
- com.oceanpayment.common.config.env.EnvAutoConfig
这样就搞定了。
- 查看自动配置报告
怎么查看自己加的自动配置类有没有被加载,或者查看所有自动配置激活的和未激活的可以通过以下几种试查看。
- spring-boot:run运行的在对话框Enviroment中加入debug=true变量
- java -jar xx.jar --debug
- main方法运行,在VM Argumanets加入-Ddebug
- 直接在application文件中加入debug=true
如果集成了spring-boot-starter-actuator监控,通过autoconfig端点也可以查看。
启动后会在控制台看到以下自动配置报告信息:
- =========================
- AUTO-CONFIGURATION REPORT
- =========================
- Positive matches:
- -----------------
- AopAutoConfiguration matched:
- - @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)
- - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)
- ...
- EnvAutoConfig matched:
- - @ConditionalOnClass found required class 'org.springframework.core.env.PropertyResolver'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- ErrorMvcAutoConfiguration matched:
- - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)
- ErrorMvcAutoConfiguration#basicErrorController matched:
- - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.ErrorController; SearchStrategy: current) did not find any beans (OnBeanCondition)
- ...
- Negative matches:
- -----------------
- ActiveMQAutoConfiguration:
- Did not match:
- - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
- AopAutoConfiguration.JdkDynamicAutoProxyConfiguration:
- Did not match:
- - @ConditionalOnProperty (spring.aop.proxy-target-class=false) found different value in property 'proxy-target-class' (OnPropertyCondition)
- ArtemisAutoConfiguration:
- Did not match:
- - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory' (OnClassCondition)
- BatchAutoConfiguration:
- Did not match:
- - @ConditionalOnClass did not find required class 'org.springframework.batch.core.launch.JobLauncher' (OnClassCondition)
- ...
Positive matches:已经启用的自动配置
Negative matches:未启用的自动配置
从报告中看到自己添加的EnvAutoConfig已经自动配置了。
- 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 |
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自动配置的更多相关文章
- Springboot 系列(三)Spring Boot 自动配置原理
注意:本 Spring Boot 系列文章基于 Spring Boot 版本 v2.1.1.RELEASE 进行学习分析,版本不同可能会有细微差别. 前言 关于配置文件可以配置的内容,在 Spring ...
- Spring Boot自动配置与Spring 条件化配置
SpringBoot自动配置 SpringBoot的自动配置是一个运行时(应用程序启动时)的过程,简化开发时间,无需浪费时间讨论具体的Spring配置,只需考虑如何利用SpringBoot的自动配置即 ...
- Spring Boot自动配置原理、实战
Spring Boot自动配置原理 Spring Boot的自动配置注解是@EnableAutoConfiguration, 从上面的@Import的类可以找到下面自动加载自动配置的映射. org.s ...
- Spring boot 自动配置自定义配置文件
示例如下: 1. 新建 Maven 项目 properties 2. pom.xml <project xmlns="http://maven.apache.org/POM/4 ...
- Spring Boot自动配置原理与实践(一)
前言 Spring Boot众所周知是为了简化Spring的配置,省去XML的复杂化配置(虽然Spring官方推荐也使用Java配置)采用Java+Annotation方式配置.如下几个问题是我刚开始 ...
- Spring Boot自动配置原理(转)
第3章 Spring Boot自动配置原理 3.1 SpringBoot的核心组件模块 首先,我们来简单统计一下SpringBoot核心工程的源码java文件数量: 我们cd到spring-boot- ...
- Spring Boot自动配置如何工作
通过使用Mongo和MySQL DB实现的示例,深入了解Spring Boot的@Conditional注释世界. 在我以前的文章“为什么选择Spring Boot?”中,我们讨论了如何创建Sprin ...
- Spring boot --- 自动配置
spring boot 自动配置 指的是针对很多spring 应用程序常见的应用功能,spring boot 能自动提供相关配置. spring boot 自动配置加载 Spring boot ...
- 使用@AutoConfigureBefore、After、Order调整Spring Boot自动配置顺序
前言 Spring Boot是Spring家族具有划时代意义的一款产品,它发展自Spring Framework却又高于它,这种高于主要表现在其最重要的三大特性,而相较于这三大特性中更为重要的便是Sp ...
随机推荐
- uva11551矩阵快速幂
题目看了半天没看懂,,就是把一个数列更新r次,每次更新就是计算和,就是每一个数,只要出现了的表号都要加上去,具体看代码 矩阵快速幂实现加速 #include<map> #include&l ...
- Aizu-2200-floyd+dp
Mr. Rito Post Office 你是一个为远程邮局邮局工作的程序员.你住的地区由几个岛屿组成.每个岛屿都有一个或多个港口城镇.除此之外,还有其他城镇和村庄.为了从一个岛到另一个岛,你必须使用 ...
- 玲珑杯 round18 A 计算几何瞎暴力
题目链接 : http://www.ifrog.cc/acm/problem/1143 当时没看到坐标的数据范围= =看到讨论才意识到,不同的坐标最多只有1k多个,完全可以暴力做法,不过也要一些技巧. ...
- UVA-1604 Cubic Eight-Puzzle (双向BFS+状态压缩+限制搜索层数)
题目大意:立体的八数码问题,一次操作是滚动一次方块,问从初始状态到目标状态的最少滚动次数. 题目分析:这道题已知初始状态和目标状态,且又状态数目庞大,适宜用双向BFS.每个小方块有6种状态,整个大方格 ...
- 057——VUE中vue-router之路由参数默认值的设置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- REST风格
1)Representational State Transfer,表述性状态转移,是一种软件架构风格 2)实现步骤 第一步:修改URL 例:http://localhost:8090/SMBMS_C ...
- c++类成员函数重载常量与非常量版本时避免代码重复的一种方法
c++有时候需要为类的某个成员函数重载常量与非常量的版本,定义常量版本是为了保证该函数可作用于常量类对象上,并防止函数改动对象内容.但有时两个版本的函数仅仅是在返回的类型不同,而在返回前做了大量相同的 ...
- AI人工智能专业词汇集
作为最早关注人工智能技术的媒体,机器之心在编译国外技术博客.论文.专家观点等内容上已经积累了超过两年多的经验.期间,从无到有,机器之心的编译团队一直在积累专业词汇.虽然有很多的文章因为专业性我们没能尽 ...
- HDU 2292
http://acm.hdu.edu.cn/showproblem.php?pid=2292 题意:1-n个节点,题目给出了完全二叉树的定义(这个定义似乎有歧义,此题以题目描述为准),且要保持最小堆性 ...
- HDU 2807
http://acm.hdu.edu.cn/showproblem.php?pid=2807 把矩阵相乘放在第二重循环,第三重循环只进行比较可以水过,优化的方法不懂 主要用这题练习floyd的写法 # ...