Spring Boot @EnableAutoConfiguration和 @Configuration的区别
Spring Boot @EnableAutoConfiguration和
@Configuration的区别
在Spring Boot中,我们会使用@SpringBootApplication来开启Spring Boot程序。在之前的文章中我们讲到了@SpringBootApplication相当于@EnableAutoConfiguration,@ComponentScan,@Configuration三者的集合。
其中@Configuration用在类上面,表明这个是个配置类,如下所示:
@Configuration
public class MySQLAutoconfiguration {
...
}
而@EnableAutoConfiguration则是开启Spring Boot的自动配置功能。什么是自动配置功能呢?简单点说就是Spring Boot根据依赖中的jar包,自动选择实例化某些配置。
接下来我们看一下@EnableAutoConfiguration是怎么工作的。
先看一下@EnableAutoConfiguration的定义:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {};
}
注意这一行: @Import(AutoConfigurationImportSelector.class)
AutoConfigurationImportSelector实现了ImportSelector接口,并会在实例化时调用selectImports。下面是其方法:
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
这个方法中的getCandidateConfigurations会从类加载器中查找所有的META-INF/spring.factories,并加载其中实现了@EnableAutoConfiguration的类。 有兴趣的朋友可以具体研究一下这个方法的实现。
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String factoryTypeName = ((String) entry.getKey()).trim();
for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
我们再看一下spring-boot-autoconfigure-2.2.2.RELEASE.jar中的META-INF/spring.factories。
spring.factories里面的内容是key=value形式的,我们重点关注一下EnableAutoConfiguration:
# Auto Configure
org.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.CloudServiceConnectorsAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
...
这里只列出了一部分内容,根据上面的代码, 所有的EnableAutoConfiguration的实现都会被自动加载。这就是自动加载的原理了。
如果我们仔细去看具体的实现:
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(JmxAutoConfiguration.class)
@ConditionalOnProperty(prefix = "spring.application.admin", value = "enabled", havingValue = "true",
matchIfMissing = false)
public class SpringApplicationAdminJmxAutoConfiguration {
可以看到里面使用了很多@Conditional*** 的注解,这种注解的作用就是判断该配置类在什么时候能够起作用。
更多教程请参考 flydean的博客
Spring Boot @EnableAutoConfiguration和 @Configuration的区别的更多相关文章
- Inspection info: Checks Spring Boot application .properties configuration files. Highlights unresolved and deprecated configuration keys and in
Cannot resolve class or package ‘jdbc’ less… (Ctrl+F1) Inspection info: Checks Spring Boot applicati ...
- Spring Boot @EnableAutoConfiguration解析
刚做后端开发的时候,最早接触的是基础的spring,为了引用二方包提供bean,还需要在xml中增加对应的包<context:component-scan base-package=" ...
- spring boot EnableAutoConfiguration exclude 无效
本文链接:https://blog.csdn.net/ID19870510/article/details/79373386 首先讲一下SpringBootApplication注解源码定义为 @Ta ...
- 【Spring Boot源码分析】@EnableAutoConfiguration注解(一)@AutoConfigurationImportSelector注解的处理
Java及Spring Boot新手,首次尝试源码分析,欢迎指正! 一.概述 @EnableAutoConfiguration注解是Spring Boot中配置自动装载的总开关.本文将从@Enable ...
- (转)Spring Boot(一)
(二期)4.springboot的综合讲解 [课程四]springbo...概念.xmind64.5KB [课程四]spring装配方式.xmind0.2MB [课程四预习]spri...解读.xmi ...
- [Spring Boot] Spring Boot启动过程源码分析
关于Spring Boot,已经有很多介绍其如何使用的文章了,本文从源代码(基于Spring-boot 1.5.6)的角度来看看Spring Boot的启动过程到底是怎么样的,为何以往纷繁复杂的配置到 ...
- Spring Boot启动过程源码分析--转
https://blog.csdn.net/dm_vincent/article/details/76735888 关于Spring Boot,已经有很多介绍其如何使用的文章了,本文从源代码(基于Sp ...
- Spring boot运行原理-自定义自动配置类
在前面SpringBoot的文章中介绍了SpringBoot的基本配置,今天我们将给大家讲一讲SpringBoot的运行原理,然后根据原理我们自定义一个starter pom. 本章对于后续继续学习S ...
- Spring Boot 笔记 (1) - Maven、基本配置、Profile的使用
一. Spring Boot 简介 开箱即用的一站式 Java EE 解决方案 Spring 技术栈的大整合 核心问题 暂时无法回答 Spring Boot 和 SOA 有什么区别? Spring B ...
随机推荐
- Otb_000_ElementUI 的 Drawer组件无法上下滚动没有滚动条
场景:当导航为侧边栏的时候,鼠标滚轮滑动的时候,以及移动端,均不可上下拖动,如果展开全部将影响操作. 解决办法: /*1.显示滚动条:当内容超出容器的时候,可以拖动:*/ .el-drawer__bo ...
- 1029 Median (25分)
Given an increasing sequence S of N integers, the median is the number at the middle position. For e ...
- Jmeter压力测试笔记(5)问题原因
压测链路是jmeter=>slb=>nginx => php=>rds 报 Too Many Connections 的原因是前端同时保持了 16000 个连接,达到实例规格的 ...
- 对EL自己以及对于param、header、cookie的相关应用的相关知识点的复习
EL表达式语言是一种可以计算和输出的java对象的简单语言. 列入请求语句为下面的方式:request.setAttribute("username","zhangsan ...
- problems
exceptionUnable to connect to userservice.shanmaohuwai.com:80 . Error #0: stream_socket_client(): un ...
- docker、docker-compose安装,卸载
docker win10安装 一.安装 https://www.docker.com/docker-windows 二.设置 控制面板-->程序-->Hyper-V linux安装: ht ...
- 插入排序(C语言版)
#include<iostream>using namespace std;int n;void lan(int a[],int size){ for(int i = 0;i < s ...
- GO代码风格指南 Uber Go (转载)
原文地址:https://github.com/uber-go/guide/blob/master/style.md 译文出处:https://github.com/uber-go/guide 本文永 ...
- python 性能测试
python中使用的性能测试模块是memory_profiler , 我们使用它里面的profile这个装饰器即可测试出我们的代码的内存使用情况了. 如果没有安装 memory_p ...
- classpath和环境变量设置(转)
classpath和环境变量设置(转) 在没有设置环境变量之前,我们可以通过直接在应用程序中加带相关信息来运行我们 的程序.比如,我们可以这样开始运行一个java程序: C:\jdk1.3.1\bin ...