2025年【面试必问】彻底搞懂Spring Boot自动装配原理及自定义starter

【面试必问】彻底搞懂Spring Boot自动装配原理及自定义starter掘金链接 https juejin cn post 一 Spring boot 组件自动装配 在 Spring boot 框架中 我们可以不必配置 xml 文件 就能完成 Bean 注入 IOC 的动作 这在之前的 Spring 是通过 xml 配置来说明要装配的组件 Spring

大家好,我是讯享网,很高兴认识大家。

掘金链接:https://juejin.cn/post//

一  Spring boot 组件自动装配

      在Spring boot框架中,我们可以不必配置xml文件,就能完成Bean注入IOC的动作。这在之前的Spring是通过xml配置来说明要装配的组件,Spring boot为了简化开发人员的配置工作,遵循"约定大于配置,配置大于编码"原则,

通过约定来实现IOC的注入,通过默认配置来代替常规的配置,从而简化了开发人员的配置和开发过程,提升研发效率。

二 Spring boot 如何实现自动装配

      整体流程是@EnableAutoConfiguration中的实现类扫描“classpath下即Pom依赖”中所有包含/META-INF/spring.factories的包,并根据其xxxAutoConfiguration和/META-INF/spring-autoconfigure-metadata.properties中的条件判断来决定是否进行自动装配。

主类设置如下

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) @EnableScheduling @EnableConfigurationProperties({GlobalConfig.class}) public class ProxyApplication { public static void main(String[] args) { SpringApplication.run(ProxyApplication.class, args); } }
讯享网

我们知道,注解SpringBootApplication是一系列注解的组合,其中包含@EnableAutoConfiguration注解

讯享网@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication {}

而根据@Enable模块驱动设计模式(即Import的类被@Configuration注解或实现ImportSelector接口,可实现注入),@EnableAutoConfiguration必然Import了“实现ImportSelector接口的实现类”,并实现其selectImport方法

// 1. Import了AutoConfigurationImportSelector类 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { } //2. 实现了DeferredImportSelector接口,并重写selectImports方法 public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered { } //3. 继承ImportSelector接口 public interface DeferredImportSelector extends ImportSelector {}

基于@Enable和selectImports装配的方式我们知道,通过selectImports方法返回需要装配的对象数组,整个搜索流程如下:

讯享网 @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return NO_IMPORTS; } AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader);//1. 获取classpath下自动加载配置的元数据 AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry( autoConfigurationMetadata, annotationMetadata); return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations()); } protected AutoConfigurationEntry getAutoConfigurationEntry( AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return EMPTY_ENTRY; } AnnotationAttributes attributes = getAttributes(annotationMetadata);//2.获取注解的属性信息 List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);//3. 获取classpath下所有enable的候装配组件 configurations = removeDuplicates(configurations); //4. 组件去重 Set<String> exclusions = getExclusions(annotationMetadata, attributes);//5. exclude去重 checkExcludedClasses(configurations, exclusions);//6. 组件去exclude configurations.removeAll(exclusions);//6. 组件去exclude configurations = filter(configurations, autoConfigurationMetadata);//7. 组件过滤 fireAutoConfigurationImportEvents(configurations, exclusions);//8. 触发自动装配监听 return new AutoConfigurationEntry(configurations, exclusions); }

整体流程:

1. 获取自动加载配置的元数据:主要是获取classpath下所有META-INF/spring-autoconfigure-metadata.properties中的配置信息,该文件里面配置的作用等同于在xxxAutoConfiguration上面的@ConditionalOnClass等注解,这么做的好处就是参考官网说明(Spring Boot uses an annotation processor to collect the conditions on auto-configurations in a metadata file (META-INF/spring-autoconfigure-metadata.properties). If that file is present, it is used to eagerly filter auto-configurations that do not match, which will improve startup time.)总而言之,加速启动时间。

2.获取注解的属性信息:这里的注解是指在主类上的注解,所以获取出来的属性信息如图所示:

3. 获取classpath下所有enable的候装配组件:获取的是META-INF/spring.factories中key为EnableAutoConfiguration的Value值的集合,此处META-INF/spring.factories可以是多个,EnableAutoConfiguration也可以是多个,此处原始数据DEBUG为118个(在spring.factories中定义的是)

4.5.6去重(此处无重复),去exclude(共2个)后,剩余116个

7.组件过滤:过滤对象是configurations,过滤条件是1中获取的autoConfigurationMetadata,过滤后,可被自动装配对象变为35个,比对删除的configurations,此处可以猜到autoConfigurationMetadata作用是配合configurations去除不符合条件的(比如当前classloader下不存在的class)configurations,同时也表明META-INF/spring-autoconfigure-metadata.properties中的Key-Value是对META-INF/spring.factories定义自动配置条件的提取。

8. 触发自动装配监听

至此,selectImports流程结束,返回需要加载对象,@Enable驱动模块完成bean的装配

三 如何自定义starter?

完成自定义starter需要包含下面三个因素:

  • 主类激活@EnableAutoConfiguration注解
  • 组件配置/META-INF/spring.factories(约定,是否将组件下某个class加入自动装配管理)
  • 实现xxxAutoConfiguration组件配置类(符合什么条件才加入自动装配)

 那么,如何自定义一个自动装配组件呢?首先,我们先要创建个普通的maven工程,并且采用{name}-spring-boot-starter 的命名风格[自定义第三方均采取此风格],也就是我们平常常说的starter启动器,引入maven依赖

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zyq</groupId> <artifactId>arthorn-spring-boot-starter</artifactId> <version>0.1.2.Release</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> <version>2.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>2.1.4.RELEASE</version> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

项目的工程目录如图所示:

1. 在resources/META-INF/spring.factories下面添加配置类ArthornAutoconfiguration

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.zyq.ArthornAutoconfiguration

2. ArthornAutoconfiguration来决定组件装配的条件;

   在此处决定是否装载ArthornService.class,比如,此处只有当classpath下存在ArthornService.class,且不存在该Bean,且存在属性arthorn.enabled=true三个条件时,才装配ArthornService.class组件.

@Configuration @EnableConfigurationProperties(ArthornProperties.class) @ConditionalOnClass(ArthornService.class) public class ArthornAutoconfiguration { @Autowired private ArthornProperties arthornProperties; @Bean @ConditionalOnMissingBean(ArthornService.class) @ConditionalOnProperty(name = "enabled",prefix = "arthorn", havingValue = "true") public ArthornService arthornService(){ ArthornService arthornService = new ArthornService(arthornProperties); return arthornService; } }

  ArthornService是我们要装配的业务组件,主要是组件的业务逻辑

public class ArthornService { private ArthornProperties arthornProperties; public ArthornService(ArthornProperties arthornProperties){ this.arthornProperties = arthornProperties; } public String kill(String blood){ if ("first".equals(blood)) return "Death is like the wind; always by my side"; else if ("second".equals(blood)) return "A sword's poor company for a long road."; else return "My honor left a long time ago."; } }

ArthornProperties用于接收在application.properties配置的属性

/ * @author zyq * @description 亚索属性配置 */ @ConfigurationProperties(prefix = "arthorn") public class ArthornProperties { private String killNum; public String getKillNum() { return killNum; } public void setKillNum(String killNum) { this.killNum = killNum; } }
小讯
上一篇 2025-02-28 19:31
下一篇 2025-01-08 19:06

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/103410.html