SpringBoot 常用注解的原理和使用
@AutoConfiguration
读取所有jar包下的 /META-INF/spring.factories
并追加到一个 LinkedMultiValueMap
中。每一个url中记录的文件路径如下:
file:/C:/Users/wangchao/apache-maven-3.5.0/repo/com/baomidou/mybatis-plus-boot-starter/3.5.1/mybatis-plus-boot-starter-3.5.1.jar!/META-INF/spring.factories
按照如下路径查看
// 1. @EnableAutoConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}
// 2. AutoConfigurationImportSelector.class#selectImports()
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}
// 3. AutoConfigurationImportSelector.class#getAutoConfigurationEntry()
protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = getConfigurationClassFilter().filter(configurations);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
// 4. AutoConfigurationImportSelector.class#getCandidateConfigurations()
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;
}
// 5. org.springframework.core.io.support.SpringFactoriesLoader#loadFactoryNames()
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
最终使用 loadSpringFactories(@Nullable ClassLoader classLoader)
方法读取所有配置文件。
// 6. org.springframework.core.io.support.SpringFactoriesLoader#loadSpringFactories()
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()) {
// 读取所有jar包下的 /META-INF/spring.factories
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);
}
}
tomcat的自动配置内置于springboot的autoconfiguration中。参考tomcat的自动配置 https://www.cnblogs.com/zhaokejin/p/15626392.html
mybatis-plus的配置没有被springboot包括。因此mybatis-stater中包含一个包mybatis-spring-boot-autoconfigure
,这其中配置了需要自动配置的类。
因此我们也可以在自己的项目下新建 /META-INF/spring.factories
,并配置自动配置类。
@Import
@Import 用于导入配置类或需要前置加载的类。被导入的类会注册为Bean,可直接作为Bean被引用。它的 value 属性可以支持三种类型:
- 被
@Configuration
修饰的配置类、或普通类(4.2版本之后可以)。 ImportSelector
接口的实现。ImportBeanDefinitionRegistrar
接口的实现。
@Import
的配置
@Configuration
@Import(value = {TestA.class, TestB.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
public class ConfigurationTest {
}
导入一个普通类
package com.example.ssmpdemo.entity;
public class TestA {
public void fun(){
System.out.println("testA");
}
}
导入一个配置类
package com.example.ssmpdemo.entity;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestB {
public void fun(){
System.out.println("testB");
}
}
通过实现 ImportSelector
接口
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.example.ssmpdemo.entity.TestC"};
}
}
通过重写 ImportBeanDefinitionRegistrar
的 registerBeanDefinitions
方法。
import com.example.ssmpdemo.entity.TestD;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
RootBeanDefinition root = new RootBeanDefinition(TestD.class);
registry.registerBeanDefinition("testD", root);
}
}
@ConfigurationProperties
- 支持常见的下划线、中划线和驼峰的转换。支持对象引导。比如:
user.friend.name
代表的是user对象中的friend对象中的name - 需要有
set()
方法 - 只添加
@ConfigurationProperties(prefix = "xxx")
并不会生效,需要配合@Configuration
让容器识别到。 @EnableConfigurationProperties(value = ConfigData.class )
会将value中指定的类注册为Bean,可直接用@AutoWired
引用。
- 定义一个类用来记录所有字段,并使用
@ConfigurationProperties(prefix = "xxx")
将数据注入到ConfigData
中。
package com.example.ssmpdemo.entity;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 用来记录Configuration的数据
* @author wangc
*/
@Data
@ConfigurationProperties(value = "spring.datasource.druid")
public class ConfigData {
private String driverClassName;
private String url;
private String username;
private String password;
}
# 对应的yml文件
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:5506/ssmpdemo?serverTimezone=UTC
username: root
password: xxxx
使用
@EnableConfigurationProperties(JDBCProperties.class)
将ConfigData
注册为Bean,并提供给ConfigurationTest
使用 。可将ConfigData
作为参数注入到构造函数和普通函数中。可以用以下方式引用被
@ConfigurationProperties(value = "spring.datasource.druid")
修饰的ConfigData
- 可以直接把
ConfigData
当成Bean
使用/**
* 可直接被注入
*/
@Autowired
private ConfigData configData;
- 可以用构造函数传入进来
@Data
@Configuration
@EnableConfigurationProperties(value = ConfigData.class )
public class ConfigurationTest {
private ConfigData configData2;
/**
* 作为构造函数的参数注入
* @param data
*/
ConfigurationTest(ConfigData data){
this.configData2 = data;
}
- 也可以作为
@Bean
的方法函数的参数。只有当前类(ConfigurationTest
)才可/**
* 直接作为函数的参数
* @param data
* @return
*/
@Bean(name = "configData2")
HashMap<String, String> getBean(ConfigData data){
return new HashMap<>(0);
}
- 可以省略
ConfigData
直接将字段注入到返回结果中。@Bean
@ConfigurationProperties(value = "spring.datasource.druid")
HashMap<String, String> getBean2(ConfigData data){
// 会自动为hashMap赋值,或使用set方法为对象赋值
return new HashMap<>();
}
EnableConfigurationProperties
注解的内部如下,它导入了一个实现了 ImportBeanDefinitionRegistrar
接口的类。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(EnableConfigurationPropertiesRegistrar.class)
class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
registerInfrastructureBeans(registry);
ConfigurationPropertiesBeanRegistrar beanRegistrar = new ConfigurationPropertiesBeanRegistrar(registry);
// 获得@EnableConfigurationProperties的value指向的对象,并注册。
getTypes(metadata).forEach(beanRegistrar::register);
}
SpringBoot 常用注解的原理和使用的更多相关文章
- SpringBoot 常用注解(持续更新)
SpringBoot 常用注解 @SpringBootApplication @Bean @ComponentScan @ControllerAdvice @ExceptionHandler @Res ...
- SpringBoot 入门篇(二) SpringBoot常用注解以及自动配置
一.SpringBoot常用注解二.SpringBoot自动配置机制SpringBoot版本:1.5.13.RELEASE 对应官方文档链接:https://docs.spring.io/spring ...
- 接近8000字的Spring/SpringBoot常用注解总结!安排!
0.前言 大家好,我是 Guide 哥!这是我的 221 篇优质原创文章.如需转载,请在文首注明地址,蟹蟹! 本文已经收录进我的 75K Star 的 Java 开源项目 JavaGuide:http ...
- Spring/SpringBoot常用注解总结
转自:[Guide哥] 0.前言 可以毫不夸张地说,这篇文章介绍的 Spring/SpringBoot 常用注解基本已经涵盖你工作中遇到的大部分常用的场景.对于每一个注解我都说了具体用法,掌握搞懂,使 ...
- SpringBoot介绍,快速入门小例子,目录结构,不同的启动方式,SpringBoot常用注解
SpringBoot介绍 引言 为了使用ssm框架去开发,准备ssm框架的模板配置 为了Spring整合第三方框架,单独的去编写xml文件 导致ssm项目后期xml文件特别多,维护xml文件的成本也是 ...
- 菜鸟的springboot常用注解总结
菜鸟的springboot常用注解总结 0.前言 可以毫不夸张地说,这篇文章介绍的 Spring/SpringBoot 常用注解基本已经涵盖你工作中遇到的大部分常用的场景.对于每一个注解我都说了具体用 ...
- 结合参数接收响应转换原理讲解SpringBoot常用注解
一.常用注解回顾 1.1 @RequestBody与@ResponseBody //注意并不要求@RequestBody与@ResponseBody成对使用. public @ResponseBody ...
- SpringBoot常用注解的介绍及使用 - 转载
常用注解 @springBootApplication 系统启动类注解,此注解是个组合注解,包括了:@SpringBootConfiguration,@EnableAutoConfiguration, ...
- springboot系列五、springboot常用注解使用说明
一.controller相关注解 1.@Controller 控制器,处理http请求. 2.@RespController Spring4之后新加的注解,原来返回json需要@ResponseBod ...
随机推荐
- Word 文字错乱,接收方显示的字体与原版不一直
原版文档使用字体的不是电脑上自带的常规字体,比如,黑软雅黑.黑体.宋体等字体.当把文档发送给其他人查阅时,字体发生了错乱,也就是字体与原版字体不一致. 需要打开"选项"设置,把非常 ...
- Shell第一章《变量》
shell前言 什么是shell shell-'壳' 命令解释器,一种应用程序 shell语言特点 SHELL语言是指UNIX操作系统的命令语言,同时又是该命令语言的解释程序的简称. Shell本身是 ...
- 「雅礼集训 2017 Day2」水箱 (数据结构+dp ,一个log)
题面 题解 在网上看到有些做法,有什么平衡树.启发式合并等等总之复杂度O(Tnlog^2(n))的不优做法,这里我就用一个O(Tnlogn)的做法好了 其实大体上推导的思路都是一样的. 我们很容易发现 ...
- 游标长时间open导致表无法vacuum问题
一.问题描述 用户在实际中可能会碰到类似以下 dead rows 无法 vacuum的问题,一个可能的原因是由于游标未结束的原因. test=# vacuum(verbose) t1; INFO: v ...
- 【读书笔记】C#高级编程 第十九章 程序集
(一)程序集的含义 程序集是.NET用于部署和配置单元的术语. .NET应用程序包含一个或多个程序集.通常扩展名是EXE或DLL的.NET可执行程序称为程序集. 程序集是自我描述的安装单元,由一个或多 ...
- PLM产品生命周期管理,包含哪些阶段?
PLM:Product Lifecycle Management=产品生命周期管理.产品的整个生命周期包括:投入期.成长期.成熟期.衰退期.结束期.PLM系统使企业可以把多年积累的所有产品相关数据放到 ...
- 关于“No loop matching the specified signature and casting was found for ufunc lstsq_n”问题的解决
下面这段代码是使用MatPlotLib绘制数据随时间变化的趋势. import datetime as dt import numpy as np import pandas as pd import ...
- 第六章:Django 综合篇 - 10:消息框架 message
在网页应用中,我们经常需要在处理完表单或其它类型的用户输入后,显示一个通知信息给用户. 对于这个需求,Django提供了基于Cookie或者会话的消息框架messages,无论是匿名用户还是认证的用户 ...
- Java容器化参数配置最佳实践
Java是以VM为基础的,而云原生讲究的就是Native,天然的矛盾,虽然Quarkus是为GraalVM和HotSpot量身定制的K8s Native Java框架,生态原因切换成本太高,这种矛盾体 ...
- Loki 简明教程
文章转载参考自:https://jishuin.proginn.com/p/763bfbd2ac34 Loki 是 Grafana Labs 团队最新的开源项目,是一个水平可扩展,高可用性,多租户的日 ...