首页 > 其他分享 >springboot启动流程 (3) 自动装配

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

时间:2023-06-21 12:23:09浏览次数:45  
标签:装配 springboot spring 流程 注解 new factories configurations

在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文件示例:

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.

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,spring,流程,注解,new,factories,configurations
From: https://www.cnblogs.com/xugf/p/17495963.html

相关文章

  • Jenkins部署前后端不分离springboot项目
    背景写这篇博客的时候我还是大学生,学校期末课程设计时要求使用Jenkins部署项目,所以使用windows,但是企业中都是使用linux,往往还会搭建一个gitlab。下面我介绍的是在window环境下使用jenkins部署项目,这阵子搞这个期末作业时感觉收获还是挺大的,专门记录下。持续集成(CI)持续集成......
  • 14. SpringMVC执行流程
    14.1、SpringMVC常用组件DispatcherServlet:前端控制器,不需要工程师开发,由框架提供作用:统一处理请求和响应,整个流程控制的中心,由它调用其它组件处理用户的请求HandlerMapping:处理器映射器,不需要工程师开发,由框架提供作用:根据请求的url、method等信息查找Handler,即控制......
  • Springboot api的controller如何接口一个List<Object>参数
    1.正常情况下,你可能会这样写:@PostMapping("/delete")@ApiOperation("Deletelistdata")@ResponseStatus(HttpStatus.OK)@ResponseBodypublicDBUpdateStatusdeleteTestCaseDatas(List<TestCaseInfo>testCaseInfoList){......
  • XXL-job开源框架相关的源码流程解析。
    XXL-job框架是一个分布式的定时任务框架。他简单快捷。配置方便。而且用途广泛。所以他的源码非常值得一看。对于我来说。其中其自写的RPC框架。以及处理发布多个定时任务的高并发处理。是我打开微服务的大门。这是一篇xxl-job源码的解析与流程分析。比较偏口语化。在这篇随笔中......
  • Springboot 框架中的Entity,Dao,Service,Controller的关系
    SpringBoot框架中的Entity,DAO,Service,Controller层的关系参考:https://blog.csdn.net/weixin_44532671/article/details/117914161https://blog.csdn.net/m0_47552180/article/details/125613332......
  • SpringBoot之MVC配置(WebMvcConfigurer详解)
    一:基本介绍SpringMVC是一种常用的JavaWeb框架,它提供了一种基于MVC模式的开发方式,可以方便地实现Web应用程序。在SpringMVC中,WebMvcConfigurer是一种常用的配置方式,可以允许我们自定义SpringMVC的行为,比如添加拦截器、消息转换器等。在本文中,我们将介绍什么是WebMvcConfi......
  • Springboot03
    1.Springboot引入JSPspring官网说,不建议springboot使用jspspring默认值支持Thymeleaf、FreeMarker·、Velocity·、GroovyJSP1.1.引入jsp相关的依赖<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId>&l......
  • 老外大型装配机程序Step7程序,西门子300P L C,非标自动化工程师可以好好学习人家先进的
    老外大型装配机程序Step7程序,西门子300PLC,非标自动化工程师可以好好学习人家先进的架构ID:3730606912832433......
  • SpringBoot学习笔记
    SpringBoot学习笔记学习资料分享,一定要点!!!示例代码跳转链接无效,查看完整笔记点击:https://gitee.com/pingWurth/study-notes/blob/master/springboot/spring-boot-demo/SpringBoot学习笔记.md官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/index......
  • Springboot web,三层架构, IOC&DI 使用总结2023
    Springbootweb,三层架构,IOC&DI使用总结2023一.spring.io全家桶springbootspringframework基础框架,配置繁琐,入门难度大--》springbootspringcloudspringsecurityspringdataspring发展到今天是一个生态圈,提供了若干个子项目,每个子项目用于完成特定的功能。二.sp......