当前位置: 代码网 > it编程>编程语言>Java > Spring Boot 自动装配原理及 Starter 实现原理解析

Spring Boot 自动装配原理及 Starter 实现原理解析

2024年09月28日 Java 我要评论
1、situation传统 spring 引入依赖时需要用 xml 或 java 显式配置,非常繁琐。2、target方便快捷地引入依赖或者配置属性。3、action3.1 @springbootap

1、situation

传统 spring 引入依赖时需要用 xml 或 java 显式配置,非常繁琐。

2、target

方便快捷地引入依赖或者配置属性。

3、action

3.1 @springbootapplication源码解析

@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 {
	@aliasfor(annotation = enableautoconfiguration.class)
	class<?>[] exclude() default {};
	@aliasfor(annotation = enableautoconfiguration.class)
	string[] excludename() default {};
	@aliasfor(annotation = componentscan.class, attribute = "basepackages")
	string[] scanbasepackages() default {};
	@aliasfor(annotation = componentscan.class, attribute = "basepackageclasses")
	class<?>[] scanbasepackageclasses() default {};
	@aliasfor(annotation = componentscan.class, attribute = "namegenerator")
	class<? extends beannamegenerator> namegenerator() default beannamegenerator.class;
	@aliasfor(annotation = configuration.class)
	boolean proxybeanmethods() default true;
}
--------------------------------------------------------
@target({elementtype.type})
@retention(retentionpolicy.runtime)
@documented
@configuration
@indexed
public @interface springbootconfiguration {
    @aliasfor(
        annotation = configuration.class
    )
    boolean proxybeanmethods() default true;
}
-------------------------------------------------------
@target(elementtype.type)
@retention(retentionpolicy.runtime)
@documented
@inherited
@autoconfigurationpackage
@import(autoconfigurationimportselector.class)
public @interface enableautoconfiguration {
	string enabled_override_property = "spring.boot.enableautoconfiguration";
	class<?>[] exclude() default {};
	string[] excludename() default {};
}

主要有springbootconfiguration、enableautoconfiguration、componentscan三个注解构成。

  • componentscan 注解的作用是扫描启动类所在的包以及子包所有bean组件并注册到 ioc 容器中,其中 excludefilters 指定了一个过滤器列表,通过两个过滤器排除某些类,比如我们可以继承 typeexcludefilter 并重写 match 方法来自定义给排除哪些类。
  • springconfiguration 注解的作用就是标记 springboot 启动类为一个配置类。
  • enableautoconfiguration 是实现自动装配的核心注解,通过@import 注解导入 autoconfigurationimportselector 类

3.2 autoconfigurationimportselector 源码

public class autoconfigurationimportselector implements deferredimportselector, beanclassloaderaware, resourceloaderaware, beanfactoryaware, environmentaware, ordered {
	@override
	public string[] selectimports(annotationmetadata annotationmetadata) {
		//1.判断自动装配开关是否打开
		if (!isenabled(annotationmetadata)) {
			return no_imports;
		}
		//2.获取所有需要装配的bean
		autoconfigurationentry autoconfigurationentry = getautoconfigurationentry(annotationmetadata);
		return stringutils.tostringarray(autoconfigurationentry.getconfigurations());
	}
	protected autoconfigurationentry getautoconfigurationentry(annotationmetadata annotationmetadata) {
		//1.再次判断自动装配开关是否打开
		if (!isenabled(annotationmetadata)) {
			return empty_entry;
		}
		//2.获取enableautoconfiguration注解中的 exclude 和 excludename
		annotationattributes attributes = getattributes(annotationmetadata);
		//3.获取需要自动装配的所有配置类,读取meta-inf/spring.factories
		//(不止读取当前项目中的meta-inf文件,所有的依赖中的meta-inf文件都会被读取)
		list<string> configurations = getcandidateconfigurations(annotationmetadata, attributes);
		//4.删除重复依赖、过滤 exclude 的依赖
		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);
	}
	...
}
------------------------------------------------------
public interface deferredimportselector extends importselector {
}
-------------------------------------------------------
public interface importselector {
    string[] selectimports(annotationmetadata var1);
}

autoconfigurationimportselector 实现了 importselector 的selectimports 方法,顾名思义就是筛选引入的依赖,那么就需要加载所有的依赖,以及条件,再根据条件对依赖进行筛选。

4、result

通过 spring boot 启动类上的 @springbootapplication 注解,spring 就可以遍历所有 meta-inf 的 spring.factories 文件中的配置类,并根据 @enableautoconfiguration 的条件选择是否将其注册为 bean。

5、面试回答

启动类的@springbootapplication注解由@springbootconfiguration,@enableautoconfiguration,@componentscan三个注解组成,三个注解共同完成自动装配;

  • @springbootconfiguration 注解标记启动类为配置类
  • @componentscan 注解实现启动时扫描启动类所在的包以及子包下所有标记为bean的类由ioc容器注册为bean
  • @enableautoconfiguration 通过 @import 注解导入
  • autoconfigurationimportselector类,然后通过autoconfigurationimportselector 类的 selectimports
  • 方法去读取需要被自动装配的组件依赖下的spring.factories文件配置的组件的类全名,并按照一定的规则过滤掉不符合要求的组件的类全名,将剩余读取到的各个组件的类全名集合返回给ioc容器并将这些组件注册为bean。

6、实现 starter 的步骤

创建 spring boot 工程,添加项目需要的依赖,spring configuration processor 这个依赖可以帮助开发者自动生成配置的的代码提示。

删除 pom.xml 的 build 部分

创建 config 文件

在 resources 文件夹下新建 meta-inf 文件夹,然后新建 spring.factories 文件,编写配置项为自动引入配置的类。

之后可以对这个项目打包,在其他的项目中通过pom.xml文件的坐标引入这个项目

在 autoconfigurationimportselector 中也可以发现com.example.demo.democonfiguration 类已经被成功加载了。

到此这篇关于spring boot 自动装配原理及 starter 实现的文章就介绍到这了,更多相关spring boot 自动装配内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com