spring 源码ConfigurationClassParser类解析收集Component、PropertySource、ComponentScan、@Import、@bean等相关注解今天分享,缘由基于spring注解配置逐步取代xml文件的配置的发展思路,也是一种趋势,比如现在常用的springboot 框架基本上都是基于注解的配置扫描,下面我们开始逐个源码分析,同时加上业务伪代码去测试,这样看起来更直观。
五种注解收集的入口如下,ConfigurationClassParser类中:
@Nullable
protected final SourceClass doProcessConfigurationClass(
ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {
//判断类上面是否有Component注解
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
//递归处理有@Component注解的内部类
processMemberClasses(configClass, sourceClass, filter);
}
// Process any @PropertySource annotations
//处理PropertySources和 PropertySource注解
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
//核心逻辑
processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}
// Process any @ComponentScan annotations
//处理ComponentScans和ComponentScan注解
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
//是否需要跳过
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
//这个parse里面的逻辑,基本上跟我们<component-scan>自定义标签解析的逻辑差不多
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
//这里又去递归,扫描到@Component生成beanDefinition后,又递归去校验类上面是否有特殊注解
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
//判断是否是候选的BeanDefinition,如果是又parse
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
//处理@Import注解 getImports(sourceClass) 获取类上面的@Import注解并封装成SourceClass
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
//处理@ImportResource注解 ,没啥用,加载xml配置文件
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
//建立xml文件和reader的映射关系
configClass.addImportedResource(resolvedResource, readerClass);
}
}
//处理@Bean注解,重点
// Process individual @Bean methods
//收集有@bean 注解的方法
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
//加入到ConfigurationClass中
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
//处理接口里面方法有@Bean注解的,逻辑差不多
// Process default methods on interfaces
processInterfaces(configClass, sourceClass);
// Process superclass, if any
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}
// No superclass -> processing is complete
return null;
}
一、@Component注解分析、
1、收集入口
//判断类上面是否有Component注解
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
//递归处理有@Component注解的内部类
processMemberClasses(configClass, sourceClass, filter);
}
点击processMemberClasses(configClass, sourceClass, filter):
private void processMemberClasses(ConfigurationClass configClass, SourceClass sourceClass,
Predicate<String> filter) throws IOException {
//获取该类的内部类并又包装成sourceClass对象
Collection<SourceClass> memberClasses = sourceClass.getMemberClasses();
if (!memberClasses.isEmpty()) {
List<SourceClass> candidates = new ArrayList<>(memberClasses.size());
for (SourceClass memberClass : memberClasses) {
//如果类是候选的
if (ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata()) &&
!memberClass.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
candidates.add(memberClass);
}
}
//排序
OrderComparator.sort(candidates);
//循环去处理每一个内部类
for (SourceClass candidate : candidates) {
if (this.importStack.contains(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
//candidate 子 configClass 父,candidate 是 configClass的内部类
//此处是递归循环调用,即一直去找下面的注解
processConfigurationClass(candidate.asConfigClass(configClass), filter);
}
finally {
this.importStack.pop();
}
}
}
}
}
2、判断是否有相关注解,点击 ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata())
public static boolean isConfigurationCandidate(AnnotationMetadata metadata) {
// Do not consider an interface or an annotation...
if (metadata.isInterface()) {
return false;
}
// Any of the typical annotations found?
for (String indicator : candidateIndicators) {//注解的集合,依次判断
if (metadata.isAnnotated(indicator)) {
return true;
}
}
// Finally, let's look for @Bean methods...
//判断是否有此@Bean注解的方法
try {
return metadata.hasAnnotatedMethods(Bean.class.getName());
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to introspect @Bean methods on class [" + metadata.getClassName() + "]: " + ex);
}
return false;
}
}
如图:
3、业务伪代码测试
import com.enjoy.jack.bean.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class InnerClassDemo {
@Component
public class SpringSource {
@Bean
public Student student() {
return new Student();
}
}
@Component
public class Mybatis {
}
}
4、测试如图
进入发现两个内部类
如果内部类有注解,就会递归循环每一个内部类
此流程收集带有@Component注解的类并放入 importStack 中,供后续业务使用。
二、@PropertySource注解分析,首先说明此注解的配置是这样的如下伪代码:
@PropertySource(name = "nandao", value = "classpath:application.properties")
public class ScanBean {
//省略其他代码.....
}
此处的注解的配置和spring.xml的配置功能是一样的,并且前几篇文章分析过了。
<!--自定义标签-->
<context:property-placeholder location="classpath:application.properties"/>
1、源码解析入口
// Process any @PropertySource annotations
//处理PropertySources和 PropertySource注解
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
//核心逻辑,点击进入
processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}
点击processPropertySource(propertySource);方法
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
String name = propertySource.getString("name");
if (!StringUtils.hasLength(name)) {
name = null;
}
String encoding = propertySource.getString("encoding");
if (!StringUtils.hasLength(encoding)) {
encoding = null;
}
//获取配置文件路径
String[] locations = propertySource.getStringArray("value");
Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");
Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));
for (String location : locations) {
try {
//替换占位符
String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
//流的方式加载配置文件并封装成Resource对象
Resource resource = this.resourceLoader.getResource(resolvedLocation);
//加载Resource中的配置属性封装成Properties对象中,并创建PropertySource对象加入到Environment对象中
addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
}
catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
// Placeholders not resolvable or resource not found when trying to open it
if (ignoreResourceNotFound) {
if (logger.isInfoEnabled()) {
logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
}
}
else {
throw ex;
}
}
}
}
测试获取的路径
点击 addPropertySource 方法
private void addPropertySource(PropertySource<?> propertySource) {
String name = propertySource.getName();
//获取Environment对象中的MutablePropertySources,并修改此参数,比如添加一下资源
MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
//如果已经存在了该配置文件的PropertySource则合并久的
if (this.propertySourceNames.contains(name)) {
// We've already added a version, we need to extend it
PropertySource<?> existing = propertySources.get(name);
if (existing != null) {
PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
((ResourcePropertySource) propertySource).withResourceName() : propertySource);
//合并二次后的类型
if (existing instanceof CompositePropertySource) {
((CompositePropertySource) existing).addFirstPropertySource(newSource);
}
else {
if (existing instanceof ResourcePropertySource) {
existing = ((ResourcePropertySource) existing).withResourceName();
}
//其实就是CompositePropertySource里面有一个Set,Set里面装了新和旧的PropertySource对象
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(newSource);
composite.addPropertySource(existing);
propertySources.replace(name, composite);
}
return;
}
}
if (this.propertySourceNames.isEmpty()) {
propertySources.addLast(propertySource);//加入 environment 对象
}
else {
//用于计算插入的位置index
String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
//吧propertySource对象存入MutablePropertySources的list中
propertySources.addBefore(firstProcessed, propertySource);
}
this.propertySourceNames.add(name);
}
加入测试
封装好之后,下游业务会对其Environment解析处理。
三、@ComponentScan注解分析
这是通过注解的方式扫描对象,原生是通过spring.xml配置实现的对比一下:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@ComponentScans({@ComponentScan("nn"), @ComponentScan("dd")})//扫描的数值目录
@Component
@ComponentScan(value = "com.enjoy.jack"/*,includeFilters = ,basePackages = */)//扫描一个目录
//<context:property-placeholder location="classpath:application.properties"/>
@PropertySource(name = "nandao", value = "classpath:application.properties")
public class ScanBean {
//省略.....
}
xml 配置
<context:component-scan base-package="com.enjoy.jack">
</context:component-scan>
1、源码入口
// Process any @ComponentScan annotations
//处理ComponentScans和ComponentScan注解
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
//是否需要跳过
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
//这个parse里面的逻辑,基本上跟我们<component-scan>自定义标签解析的逻辑差不多
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
//这里又去递归,扫描到@Component生成beanDefinition后,又递归去校验类上面是否有特殊注解
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
//判断是否是候选的BeanDefinition,如果是又parse
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
测试走到这里
2、点击 AnnotationConfigUtils.attributesForRepeatable()
static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata,
Class<?> containerClass, Class<?> annotationClass) {
return attributesForRepeatable(metadata, containerClass.getName(), annotationClass.getName());//点击进入
}
测试如图
来到
@SuppressWarnings("unchecked")
static Set<AnnotationAttributes> attributesForRepeatable(
AnnotationMetadata metadata, String containerClassName, String annotationClassName) {
Set<AnnotationAttributes> result = new LinkedHashSet<>();
// Direct annotation present?
addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false));//点击
// Container annotation present?
Map<String, Object> container = metadata.getAnnotationAttributes(containerClassName, false);
if (container != null && container.containsKey("value")) {
for (Map<String, Object> containedAttributes : (Map<String, Object>[]) container.get("value")) {
addAttributesIfNotNull(result, containedAttributes);
}
}
// Return merged result
return Collections.unmodifiableSet(result);
}
点击addAttributesIfNotNull
private static void addAttributesIfNotNull(
Set<AnnotationAttributes> result, @Nullable Map<String, Object> attributes) {
if (attributes != null) {
result.add(AnnotationAttributes.fromMap(attributes));
}
}
测试数据
返回扫描到注解的三个目录
3、下面开始判断并依次扫描每个目录下的文件 ,判断逻辑,this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) 进入
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
//此处业务场景,直接返回 false
if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
return false;
}
if (phase == null) {
if (metadata instanceof AnnotationMetadata &&
ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
}
return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
}
List<Condition> conditions = new ArrayList<>();
//获取@Conditional注解的value值
for (String[] conditionClasses : getConditionClasses(metadata)) {
for (String conditionClass : conditionClasses) {
//反射实例化Condition对象
Condition condition = getCondition(conditionClass, this.context.getClassLoader());
conditions.add(condition);
}
}
//排序
AnnotationAwareOrderComparator.sort(conditions);
//调用每一个condition的matches方法
for (Condition condition : conditions) {
ConfigurationPhase requiredPhase = null;
if (condition instanceof ConfigurationCondition) {
requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
}
//调用matches方法
if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
return true;
}
}
return false;
}
返回 封装了13个beanDefinition对象
然后继续递归循环调用,即继续生成 BeanDefinition 对象。
到此、三种常用的注解分析完毕,大家一定要多多思考,上下分析、前后联系起来,定会进步很快,下篇会分析另外三种注解,敬请期待!