1. 简介

通过源码探究SpringBoot的自动装配功能。

2. 核心代码

2.1 启动类

我们都知道SpringBoot项目创建好后,会自动生成一个当前模块的启动类。如下:

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. @SpringBootApplication
  4. public class TestApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(TestApplication.class, args);
  7. }
  8. }

2.2 @SpringBootApplication

在启动类中有个很重要的注解@SpringBootApplication,在该注解中除了元注解,就是@SpringBootConfiguration

@EnableAutoConfiguration@ComponentScan

  • @SpringBootConfiguration:标识了当前类为配置类
  • @ComponentScan:配置类的组件扫描
  • @EnableAutoConfiguration:激活自动装配
  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @SpringBootConfiguration
  6. @EnableAutoConfiguration
  7. @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  8. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  9. public @interface SpringBootApplication {
  10. /**
  11. * 排除特定的自动配置类,以便它们永远不会被应用
  12. */
  13. @AliasFor(annotation = EnableAutoConfiguration.class)
  14. Class<?>[] exclude() default {};
  15. /**
  16. * 排除特定的自动配置类名称,以便它们永远不会被
  17. */
  18. @AliasFor(annotation = EnableAutoConfiguration.class)
  19. String[] excludeName() default {};
  20. /**
  21. * 用于扫描带注释组件的基本包。
  22. */
  23. @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
  24. String[] scanBasePackages() default {};
  25. /**
  26. * 用于指定要扫描带注释组件的包。将扫描指定的每个类的包。
  27. */
  28. @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
  29. Class<?>[] scanBasePackageClasses() default {};
  30. ...
  31. }

2.3 @EnableAutoConfiguration

这里我们重点看@EnableAutoConfiguration注解。

在该注解中我们看到了熟悉的@Import注解,并且该注解指定导入了AutoConfigurationImportSelector.class

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @AutoConfigurationPackage
  6. @Import(AutoConfigurationImportSelector.class)
  7. public @interface EnableAutoConfiguration {
  8. String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
  9. Class<?>[] exclude() default {};
  10. String[] excludeName() default {};
  11. }

2.4 AutoConfigurationImportSelector

我们进入到AutoConfigurationImportSelector.class,看到当前类继承自DeferredImportSelector接口,而通过查看DeferredImportSelector源码 public interface DeferredImportSelector extends ImportSelector {}得知,DeferredImportSelector继承自ImportSelector接口。因此我们大概得知SpringBoot默认装载了ImportSelector::selectImports()方法返回的全限类名数组。

  1. public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
  2. ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
  3. /**
  4. * 重写ImportSelector接口中的selectImports方法
  5. * <p>
  6. * 该方法返回的数组<全限类名> 都将被装载到IOC容器
  7. */
  8. @Override
  9. public String[] selectImports(AnnotationMetadata annotationMetadata) {
  10. if (!isEnabled(annotationMetadata)) {
  11. return NO_IMPORTS;
  12. }
  13. AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);
  14. // 将符合注入IOC条件的Bean类信息返回
  15. return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
  16. }
  17. /**
  18. * 获取自动配置的信息
  19. */
  20. protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
  21. if (!isEnabled(annotationMetadata)) {
  22. return EMPTY_ENTRY;
  23. }
  24. // 获取元注解属性
  25. AnnotationAttributes attributes = getAttributes(annotationMetadata);
  26. // ** 获取候选的配置信息
  27. List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
  28. // 移除重复元素
  29. configurations = removeDuplicates(configurations);
  30. // 获取任何限制候选配置的排除项
  31. Set<String> exclusions = getExclusions(annotationMetadata, attributes);
  32. // 判断排除项是否存在
  33. checkExcludedClasses(configurations, exclusions);
  34. // 从候选配置集合中排除需要排除的项
  35. configurations.removeAll(exclusions);
  36. // 获取在spring.factories中注册的过滤器,并执行filter方法,返回符合注册条件的元素
  37. configurations = getConfigurationClassFilter().filter(configurations);
  38. // 触发自动配置导入事件
  39. fireAutoConfigurationImportEvents(configurations, exclusions);
  40. // 返回自动配置和排除项信息
  41. return new AutoConfigurationEntry(configurations, exclusions);
  42. }
  43. /**
  44. * 获取属性
  45. */
  46. protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) {
  47. String name = getAnnotationClass().getName();
  48. AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(name, true));
  49. Assert.notNull(attributes, () -> "No auto-configuration attributes found. Is " + metadata.getClassName()
  50. + " annotated with " + ClassUtils.getShortName(name) + "?");
  51. return attributes;
  52. }
  53. /**
  54. * 获取候选的配置信息
  55. */
  56. protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
  57. List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
  58. getBeanClassLoader());
  59. // 这个就很重要了,从这里大概可以判断出 配置信息是从META-INF/spring.factories这个文件中获取到的
  60. Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
  61. + "are using a custom packaging, make sure that file is correct.");
  62. return configurations;
  63. }
  64. }

2.5 SpringFactoriesLoader

为了验证配置信息是不是从META-INF/spring.factories获取的,我们继续跟踪源码SpringFactoriesLoader::loadFactoryNames()

  1. public final class SpringFactoriesLoader {
  2. /**
  3. * 工厂资源位置
  4. *
  5. * <p>
  6. * 可以存在于多个Jar文件中
  7. */
  8. public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
  9. static final Map<ClassLoader, Map<String, List<String>>> cache = new ConcurrentReferenceHashMap<>();
  10. /**
  11. * 加载工厂名称
  12. *
  13. */
  14. public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
  15. ClassLoader classLoaderToUse = classLoader;
  16. if (classLoaderToUse == null) {
  17. classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
  18. }
  19. // 当前上下文中 factoryTypeName = EnableAutoConfiguration注解的全限类名
  20. String factoryTypeName = factoryType.getName();
  21. return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
  22. }
  23. /**
  24. * 加载spring工厂
  25. */
  26. private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
  27. Map<String, List<String>> result = cache.get(classLoader);
  28. if (result != null) {
  29. return result;
  30. }
  31. result = new HashMap<>();
  32. try {
  33. // 获取 META-INF/spring.factories 枚举信息
  34. Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
  35. while (urls.hasMoreElements()) {
  36. // spring.factories 文件地址
  37. URL url = urls.nextElement();
  38. // 获取resource信息
  39. UrlResource resource = new UrlResource(url);
  40. // 加载配置文件中的配置信息
  41. Properties properties = PropertiesLoaderUtils.loadProperties(resource);
  42. // 遍历配置信息放入全局的Map缓存中
  43. for (Map.Entry<?, ?> entry : properties.entrySet()) {
  44. String factoryTypeName = ((String) entry.getKey()).trim();
  45. String[] factoryImplementationNames =
  46. StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
  47. for (String factoryImplementationName : factoryImplementationNames) {
  48. result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>())
  49. .add(factoryImplementationName.trim());
  50. }
  51. }
  52. }
  53. // Replace all lists with unmodifiable lists containing unique elements
  54. result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
  55. .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
  56. cache.put(classLoader, result);
  57. }
  58. catch (IOException ex) {
  59. throw new IllegalArgumentException("Unable to load factories from location [" +
  60. FACTORIES_RESOURCE_LOCATION + "]", ex);
  61. }
  62. return result;
  63. }
  64. }

在这里为了更方便的查看loadSpringFactories中各步骤是用来干嘛的,特意添加debug截图如下:

2.6 spring.factories

spring-boot-autoconfigure下的META-INF/spring.factories文件信息

从上图中我们能看出spring.factories 中指定了很多常用中间件的auto configure文件信息。

2.7 RedisAutoConfiguration

我们仅查看我们比较熟悉的redis中间件的autoconfiguration文件信息

RedisAutoConfiguration源码中我们能看出在文件中使用很多的@Conditional注解来实现注入符合条件的SpringBean

  1. // 标识为配置类
  2. @Configuration(proxyBeanMethods = false)
  3. // 当存在RedisOperations.class时注入当前类
  4. @ConditionalOnClass(RedisOperations.class)
  5. // 激活RedisProperties属性文件
  6. @EnableConfigurationProperties(RedisProperties.class)
  7. // 导入客户端配置类
  8. @Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
  9. public class RedisAutoConfiguration {
  10. @Bean
  11. // 当 当前环境中没有redisTemplate Bean时注入当前Bean
  12. @ConditionalOnMissingBean(name = "redisTemplate")
  13. /*
  14. * 当指定RedisConnectionFactory类已存在于 BeanFactory 中,并且可以确定单个候选项才会匹配成功。
  15. * 或者 BeanFactory 存在多个 RedisConnectionFactory 实例,但是有一个 primary 候选项被指定(通常在类上使用 @Primary * 注解),也会匹配成功
  16. */
  17. @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
  18. public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
  19. RedisTemplate<Object, Object> template = new RedisTemplate<>();
  20. template.setConnectionFactory(redisConnectionFactory);
  21. return template;
  22. }
  23. @Bean
  24. @ConditionalOnMissingBean
  25. @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
  26. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
  27. StringRedisTemplate template = new StringRedisTemplate();
  28. template.setConnectionFactory(redisConnectionFactory);
  29. return template;
  30. }
  31. }

3. 小结

至此我们大概了解了SpringBoot是如何实现自动装配的。

  1. 项目启动
  2. 通过启动类上的@SpringBootApplication注解加载@EnableAutoConfiguration注解
  3. 通过@EnableAutoConfiguration加载@Import(AutoConfigurationImportSelector.class)执行AutoConfigurationImportSelector导入选择器
  4. AutoConfigurationImportSelector中执行selectImports()方法
  5. AutoConfigurationImportSelector::selectImports()通过加载ClassPath下的META-INF/spring.factories文件来动态的注入*AutoConfiguration类
  6. *AutoConfiguration类中通过使用@Conditional注解及其派生注解实现了Bean的灵活装载。

SpringBoot自动装配-源码分析的更多相关文章

  1. SpringBoot源码学习1——SpringBoot自动装配源码解析+Spring如何处理配置类的

    系列文章目录和关于我 一丶什么是SpringBoot自动装配 SpringBoot通过SPI的机制,在我们程序员引入一些starter之后,扫描外部引用 jar 包中的META-INF/spring. ...

  2. SpringBoot启动代码和自动装配源码分析

    ​ 随着互联网的快速发展,各种组件层出不穷,需要框架集成的组件越来越多.每一种组件与Spring容器整合需要实现相关代码.SpringMVC框架配置由于太过于繁琐和依赖XML文件:为了方便快速集成第三 ...

  3. 原创001 | 搭上SpringBoot自动注入源码分析专车

    前言 如果这是你第二次看到师长的文章,说明你在觊觎我的美色!O(∩_∩)O哈哈~ 点赞+关注再看,养成习惯 没别的意思,就是需要你的窥屏^_^ 本系列为SpringBoot深度源码专车系列,第一篇发车 ...

  4. SpringBoot自动装配源码解析

    序:众所周知spring-boot入门容易精通难,说到底spring-boot是对spring已有的各种技术的整合封装,因为封装了所以使用简单,也因为封装了所以越来越多的"拿来主义" ...

  5. SpringBoot自动装配源码

    前几天,面试的时候被问到了SpringBoot的自动装配的原理.趁着五一的假期,就来整理一下这个流程. 我这里使用的是idea创建的最简单的SpringBoot项目. 我们都知道,main方法是jav ...

  6. SpringBoot自动配置源码调试

    之前对SpringBoot的自动配置原理进行了较为详细的介绍(https://www.cnblogs.com/stm32stm32/p/10560933.html),接下来就对自动配置进行源码调试,探 ...

  7. Spring Boot 自动配置 源码分析

    Spring Boot 最大的特点(亮点)就是自动配置 AutoConfiguration 下面,先说一下 @EnableAutoConfiguration ,然后再看源代码,到底自动配置是怎么配置的 ...

  8. springboot整合mybatis源码分析

    springboot整合mybatis源码分析 本文主要讲述mybatis在springboot中是如何被加载执行的,由于涉及的内容会比较多,所以这次只会对调用关系及关键代码点进行讲解,为了避免文章太 ...

  9. tomcat源码--springboot整合tomcat源码分析

    1.测试代码,一个简单的springboot web项目:地址:https://gitee.com/yangxioahui/demo_mybatis.git 一:tomcat的主要架构:1.如果我们下 ...

随机推荐

  1. 教你用python搭建一个「生活常识解答」机器人

    今天教大家如何用Python爬虫去搭建一个「生活常识解答」机器人. 思路:这个机器人主要是依托于"阿里达摩院发布的语言模型PLUG",通过爬虫的方式,发送post请求(提问),然后 ...

  2. Java安全之Weblogic内存马

    Java安全之Weblogic内存马 0x00 前言 发现网上大部分大部分weblogic工具都是基于RMI绑定实例回显,但这种方式有个弊端,在Weblogic JNDI树里面能将打入的RMI后门查看 ...

  3. Centos7安装部署搭建gitlab平台、汉化

    Centos7安装部署搭建gitlab平台.汉化 安装环境要求:内存不要小于4G,否则后期web界面可能会报错 一.准备工作 1.1 查看系统版本 首先查询系统版本,下载Gitlab的对应版本 [ro ...

  4. 我是怎么写 Git Commit message 的?

    目录 作用 用的什么规范? type scope subject body footer 参考文章 用的什么辅助工具? 作用 编写格式化的 commit message 能够大大提高代码的维护效率. ...

  5. Vue 前端权限控制的优化改进版

    1.前言   之前<Vue前端访问控制方案 >一文中提出,使用class="permissions"结合元素id来标识权限控制相关的dom元素,并通过公共方法check ...

  6. 48、django工程(model)

    48.1.数据库配置: 1.django默认支持sqlite,mysql, oracle,postgresql数据库: (1)sqlite: django默认使用sqlite的数据库,默认自带sqli ...

  7. 2018-10-14普及模拟赛」Hash 键值 (hash)

    今天,带大家看一看一道思维题... Hash 键值 (hash) 题目描述 Marser沉迷hash无法自拔,然而他发现自己记不住hash键值了-- Marser使用的hash函数是一个单纯的取模运算 ...

  8. NoSql非关系型数据库之MongoDB应用(一):安装MongoDB服务

    业精于勤,荒于嬉:行成于思,毁于随. 一.MongoDB服务下载安装(windows环境安装) 1.进入官网:https://www.mongodb.com/,点击右上角的 Try Free  , 2 ...

  9. activiti版本下载

    activiti工作流历史各个版本下载地址修改版本号后在浏览器地址栏回车即可 例如: https://github.com/Activiti/Activiti/releases/download/ac ...

  10. 其他:压力测试Jmeter工具使用

    下载路径: http://yd01.siweidaoxiang.com:8070/jmeter_52z.com.zip 配置汉化中文: 找到jmeter的安装目录:打开 \bin\jmeter.pro ...