springboot启动流程 (3) 自动装配

这篇具有很好参考价值的文章主要介绍了springboot启动流程 (3) 自动装配。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

在SpringBoot中,EnableAutoConfiguration注解用于开启自动装配功能。

本文将详细分析该注解的工作流程。

EnableAutoConfiguration注解

启用SpringBoot自动装配功能,尝试猜测和配置可能需要的组件Bean。

自动装配类通常是根据类路径和定义的Bean来应用的。例如,如果类路径上有tomcat-embedded.jar,那么可能需要一个TomcatServletWebServerFactory(除非已经定义了自己的Servlet WebServerFactory Bean)。

自动装配试图尽可能地智能化,并将随着开发者定义自己的配置而取消自动装配相冲突的配置。开发者可以使用exclude()排除不想使用的配置,也可以通过spring.autoconfig.exclude属性排除这些配置。自动装配总是在用户定义的Bean注册之后应用。

用@EnableAutoConfiguration注解标注的类所在包具有特定的意义,通常用作默认扫描的包。通常建议将@EnableAutoConfiguration(如果没有使用@SpringBootApplication注解)放在根包中,以便可以搜索所有子包和类。

自动装配类是普通的Spring @Configuration类,使用SpringFactoriesLoader机制定位。通常使用@Conditional方式装配,最常用的是@ConditionalOnClass和@ConditionalOnMissingBean注解。

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 */
	Class<?>[] exclude() default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 * 当类路径下没有指定的类时,可以使用这个属性指定排除的类
	 */
	String[] excludeName() default {};
}

该注解Import了AutoConfigurationImportSelector类,AutoConfigurationImportSelector类实现了DeferredImportSelector接口。

Import注解和DeferredImportSelector接口在之前的"Spring @Import注解源码分析"中详细分析过,此处在介绍它们,只分析AutoConfigurationImportSelector的工作流程。

AutoConfigurationImportSelector类

DeferredImportSelector接口

A variation of ImportSelector that runs after all @Configuration beans have been processed. This type of selector can be particularly useful when the selected imports are @Conditional.

Implementations can also extend the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation to indicate a precedence against other DeferredImportSelectors.

Implementations may also provide an import group which can provide additional sorting and filtering logic across different selectors.

AutoConfigurationGroup类

AutoConfigurationImportSelector的getImportGroup方法返回了AutoConfigurationGroup类。

private static class AutoConfigurationGroup implements 
		DeferredImportSelector.Group, BeanClassLoaderAware, BeanFactoryAware, ResourceLoaderAware {

	private final Map<String, AnnotationMetadata> entries = new LinkedHashMap<>();

	private final List<AutoConfigurationEntry> autoConfigurationEntries = new ArrayList<>();

	// ... 略

	@Override
	public void process(
			AnnotationMetadata annotationMetadata,
			DeferredImportSelector deferredImportSelector) {

		// AutoConfigurationEntry类使用List保存Configuration类
		AutoConfigurationEntry autoConfigurationEntry =
            ((AutoConfigurationImportSelector) deferredImportSelector)
				.getAutoConfigurationEntry(annotationMetadata);

		this.autoConfigurationEntries.add(autoConfigurationEntry);
		for (String importClassName : autoConfigurationEntry.getConfigurations()) {
			this.entries.putIfAbsent(importClassName, annotationMetadata);
		}
	}

	@Override
	public Iterable<Entry> selectImports() {
		// 查找排除的配置类
		Set<String> allExclusions = this.autoConfigurationEntries.stream()
				.map(AutoConfigurationEntry::getExclusions)
				.flatMap(Collection::stream)
				.collect(Collectors.toSet());
		// 所有配置类
		Set<String> processedConfigurations = this.autoConfigurationEntries.stream()
				.map(AutoConfigurationEntry::getConfigurations)
				.flatMap(Collection::stream)
				.collect(Collectors.toCollection(LinkedHashSet::new));
		// 将排除的配置类移除掉
		processedConfigurations.removeAll(allExclusions);

		// 排序
		return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream()
				.map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName))
				.collect(Collectors.toList());
	}

	// ... 略
}

从上面的代码可以看出,查找自动装配类的逻辑在getAutoConfigurationEntry方法中。

getAutoConfigurationEntry方法

从META-INF/spring.factories文件解析EnableAutoConfiguration配置。

META-INF/spring.factories文件示例:

springboot启动流程 (3) 自动装配

protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
	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);
	// 这里的Filter是从META-INF/spring.factories文件解析出来的
	configurations = getConfigurationClassFilter().filter(configurations);
	// 触发事件
	fireAutoConfigurationImportEvents(configurations, exclusions);
	return new AutoConfigurationEntry(configurations, exclusions);
}

protected List<String> getCandidateConfigurations(
		AnnotationMetadata metadata, AnnotationAttributes attributes) {
	// 从META-INF/spring.factories文件查找EnableAutoConfiguration配置
	List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
						getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
	return configurations;
}

SpringFactoriesLoader类loadFactoryNames方法

Load the fully qualified class names of factory implementations of the given type from "META-INF/spring.factories", using the given class loader.文章来源地址https://www.toymoban.com/news/detail-493486.html

public static List<String> loadFactoryNames(Class<?> factoryType, ClassLoader classLoader) {
	String factoryTypeName = factoryType.getName();
	return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}

private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
	MultiValueMap<String, String> result = cache.get(classLoader);
	if (result != null) {
		return result;
	}

	try {
		// FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"
		// 从类路径下查找META-INF/spring.factories文件
		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 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);
	}
}

到了这里,关于springboot启动流程 (3) 自动装配的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot源码-自动装配

      springboot的核心注解@SpringBootApplication 接着看 @SpringBootApplication 注解 截图: 代码:  接着看红框的注解 @EnableAutoConfiguration 截图: 代码:  接着看红框的 AutoConfigurationImportSelector.class 这个类 截图: 接着看接口 DeferredImportSelector 的实现 截图: 在这个DeferredImportSelector类中,

    2024年02月08日
    浏览(28)
  • springBoot自动装配机制

    自动配置原理 @SpringBootApplication 是一个组合注解,由 @ComponentScan、@EnableAutoConfiguration 和 @SpringBootConfiguration 组成 @SpringBootConfiguration 与普通 @Configuration 相比,唯一区别是前者要求整个 app 中只出现一次 @ComponentScan excludeFilters - 用来在组件扫描时进行排除,也会排除自动配置类

    2024年02月08日
    浏览(37)
  • springboot自动装配大概原理

    自动装配 : pom.xml spring-boot-dependence:核心都依赖在父类工程中! 我们在写入或者引入springboot依赖的时候,不需要指定版,因为有这些仓库的版本 启动器:------spring boot的启动场景 比如spring-boot-starter-web,他就会帮我们导入web环境苏需要的依赖。 springboot会将所有的功能场景

    2023年04月25日
    浏览(26)
  • SpringBoot自动装配原理及分析

    在使用SpringBoot的时候,会自动将Bean装配到IOC容器中。例如我们在使用Redis数据库的时候,会引入依赖spring-boot-starter-data-redis。在引入这个依赖后,服务初始化的时候,会将操作Redis需要的组件注入到Ioc容器中进行后续使用。 自动装配的大致过程如下: 获取到组件(spring-boo

    2024年01月21日
    浏览(32)
  • 【Spring】深究SpringBoot自动装配原理

    早期的 Spring 项目需要添加需要配置繁琐的 xml ,比如 MVC 、事务、数据库连接等繁琐的配置。 Spring Boot 的出现就无需这些繁琐的配置,因为 Spring Boot 基于 约定大于配置 的理念,在项目启动时候,将约定的配置类自动装配到 IOC 容器里。 这些都因为 Spring Boot 有自动装配的特性

    2024年02月14日
    浏览(26)
  • 一文足够,SpringBoot自动装配底层源码

    目录 自动装配原理 开始深入源码 总结自动装配原理 首先明白一个概念,什么是自动装配? 我们在项目中建一个yaml或者properties文件,里面配置一些参数,如redis,在pom中引入启动器,之后就能用redis,自动把这些集成到spring中,这就是自动装配。 先来提前剧透: 加载spring.

    2023年04月13日
    浏览(30)
  • SpringBoot@Autowired自动装配失败解决方法

    今天写SpringBoot项目的时候,使用@Autowired注解idea报错了,那就记录一下怎么解决的吧。 打开idea的setting(设置)然后搜索inspection(检查) 然后找到Spring下的Spring Core的Code(代码)找到Autowired for bean class( Spring bean 注入点的自动装配问题),然后改成warning就可以了

    2024年02月12日
    浏览(30)
  • SpringBoot自动装配—简化依赖管理的利器

    在现代的软件开发中,依赖管理是一个关键的任务。随着应用程序规模的增长,手动管理对象之间的依赖关系变得越来越复杂。为了解决这个问题,Spring Boot 提供了一种强大的功能,即自动装配(Autowiring)。本文将深入探讨 Spring Boot 中的自动装配原理和使用方法,并通过具

    2024年02月05日
    浏览(25)
  • SpringBoot自动装配原理学习与实战运用

    我们知道SpringBoot就是框架的框架,它解决了Spring在开发过程中繁琐的配置问题。例如在引入web、aop、data、cache等等场景,以往我们使用Spring时,会需要向容器中手动配置DispatchServlet、 AspectJAutoProxyingConfiguration等等配置类,而使用SpringBoot框架后,只需要引入spring-boot-starter-xx

    2023年04月13日
    浏览(30)
  • 手写一个starter来理解SpringBoot的自动装配

    自动装配是指SpringBoot在启动的时候会自动的将系统中所需要的依赖注入进Spring容器中 我们可以点开 @SpringBootApplication 这个注解来一探究竟 点开这个注解可以发现这些 我们点开 @SpringBootConfiguration 这个注解 可以发现实际上 @SpringBootApplication 这个其实是一个配置类 再点开 @En

    2024年01月23日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包