概述
bean的定义与注册源码相对比较简单,本文主要根据Spring启动流程 介绍spring配置类的注册与定义
一、先看demo
/**
* spring生命周期配置类<后续会继续分析生命周期>
**/
@Configuration
@ComponentScan("com.jj.stu.spring.cycle")
@Conditional(MyCondition.class)
public class SpringCycleConfig implements InitializingBean {
public SpringCycleConfig() {
System.out.println("spring配置类实例化");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("SpringCycleConfig bean初始化接口 InitializingBean" );
}
}
/**
* 条件判断类
**/
public class MyCondition implements Condition {
/**
* 根据条件判断上下文context
*/
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 1.获取当前环境配置
Environment environment = context.getEnvironment();
String osName = environment.getProperty("os.name");
if (osName.equals("Windows 7")) {
// 返回true 就是能够创建该bean
return true;
}
return false;
}
}
//启动类
public class SpringCycleMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringCycleConfig.class);
context.close();
}
}
二、AnnotationConfigApplicationContext源码分析
直接看代码,以构造函数为切入点
//1.调用无参构造器 2.注册配置类 3.调用refresh方法
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
this.register(componentClasses);
this.refresh();
}
关于配置类bean的定义与注册看前两个方法就好
顺便说一下refresh方法,对bean生命周期进行管理主要是通过这个方法,后续会讲
1.this()方法源码
public AnnotationConfigApplicationContext() {
//这个是AnnotatedBeanDefinitionReader,beandefinition读取器 重点分析
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
//重点有两条
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
this.beanNameGenerator = AnnotationBeanNameGenerator.INSTANCE;
this.scopeMetadataResolver = new AnnotationScopeMetadataResolver();
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
//1.条件评估器 在注册时进行条件判断,后文解析doRegisterBean()时再分析源码
this.conditionEvaluator = new ConditionEvaluator(registry, environment, (ResourceLoader)null);
2.注册spring内置的后置处理器,生命周期管理基本全靠这些处理器
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry)源码
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {
//获取registry注册器中的beanFactory
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
//1.设置spring容器中的bean的排序处理器
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
//2.设置spring容器中的匹配依赖项候选者的策略接口 (此接口解析请移步最后)
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
//3. 下面是注入默认的5个bean级与beanfactory级的后置处理器
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet(8);
RootBeanDefinition def;
if (!registry.containsBeanDefinition("org.springframework.context.annotation.internalConfigurationAnnotationProcessor")) {
// 注入配置类后置处理器
def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"));
}
if (!registry.containsBeanDefinition("org.springframework.context.annotation.internalAutowiredAnnotationProcessor")) {
// 注入依赖注入后置处理器bean
def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalAutowiredAnnotationProcessor"));
}
if (jsr250Present && !registry.containsBeanDefinition("org.springframework.context.annotation.internalCommonAnnotationProcessor")) {
def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalCommonAnnotationProcessor"));
}
if (jpaPresent && !registry.containsBeanDefinition("org.springframework.context.annotation.internalPersistenceAnnotationProcessor")) {
def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName("org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor", AnnotationConfigUtils.class.getClassLoader()));
} catch (ClassNotFoundException var6) {
throw new IllegalStateException("Cannot load optional framework class: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor", var6);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalPersistenceAnnotationProcessor"));
}
if (!registry.containsBeanDefinition("org.springframework.context.event.internalEventListenerProcessor")) {
//注入事件监听后置处理器
def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.event.internalEventListenerProcessor"));
}
if (!registry.containsBeanDefinition("org.springframework.context.event.internalEventListenerFactory")) {
def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.event.internalEventListenerFactory"));
}
return beanDefs;
}
其中ConfigurationClassPostProcessor用于解析处理@Configuration表示的配置类,包括配置类中可能出现的@ComponentScan、@Import、@Bean等,非常重要。
AutowiredAnnotationBeanPostProcessor则是用于解析处理@Autowired等表示的bean,其原理是通过递归查找、注入所有父类中出现的spring bean。
至此内置处理器bean注入完成,效果如下
2. this.register(componentClasses);源码分析
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers,
@Nullable Supplier<T> supplier, @Nullable BeanDefinitionCustomizer[] customizers) {
//获取当前class的AnnotatedGenericBeanDefinition
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
//根据配置类上的condition判断是否注册进入beanfactory 解析请看下文
if (!this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
abd.setInstanceSupplier(supplier);
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
String beanName = name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry);
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
int var10;
int var11;
if (qualifiers != null) {
Class[] var9 = qualifiers;
var10 = qualifiers.length;
for(var11 = 0; var11 < var10; ++var11) {
Class<? extends Annotation> qualifier = var9[var11];
if (Primary.class == qualifier) {
abd.setPrimary(true);
} else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
} else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
if (customizers != null) {
BeanDefinitionCustomizer[] var13 = customizers;
var10 = customizers.length;
for(var11 = 0; var11 < var10; ++var11) {
BeanDefinitionCustomizer customizer = var13[var11];
customizer.customize(abd);
}
}
//最后将bean解析成BeanDefinition 注册到beanFactory中
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
}
这个方法比较简单,调试几遍看看注释就能弄懂,
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
//1.元数据不为null 并且含有@condition,不含直接返回false
if (metadata != null && metadata.isAnnotated(Conditional.class.getName())) {
//第一次必为null
if (phase == null) {
//2.判断是配置类还是注册bean,并且给phase赋值 递归调用此方法
return metadata instanceof AnnotationMetadata && ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata)metadata) ? this.shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION) : this.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
} else {
//3.这里是获取当前bean上@Conditional中所有的条件类,
List<Condition> conditions = new ArrayList();
Iterator var4 = this.getConditionClasses(metadata).iterator();
while(var4.hasNext()) {
String[] conditionClasses = (String[])var4.next();
String[] var6 = conditionClasses;
int var7 = conditionClasses.length;
for(int var8 = 0; var8 < var7; ++var8) {
String conditionClass = var6[var8];
Condition condition = this.getCondition(conditionClass, this.context.getClassLoader());
conditions.add(condition);
}
}
AnnotationAwareOrderComparator.sort(conditions);
var4 = conditions.iterator();
Condition condition;
ConfigurationPhase requiredPhase;
do {
do {
//5.条件类遍历完毕,
if (!var4.hasNext()) {
return false;
}
//6.更新condition为下1个
condition = (Condition)var4.next();
requiredPhase = null;
if (condition instanceof ConfigurationCondition) {
requiredPhase = ((ConfigurationCondition)condition).getConfigurationPhase();
}
} while(requiredPhase != null && requiredPhase != phase);
//4.循环调用所有条件类的匹配方法
} while(condition.matches(this.context, metadata));
return true;
}
} else {
return false;
}
}
至此配置类注入完成,接下来看看效果
通过修改demo中MyCondition类matchs方法返回值,则可以验证shouldSkip方法的效果,请看:
三、浅析refresh()
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
/**********************以下是BeanFactory的创建及预准备工作 *************/
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
//***********************以下是通过反射机制实例化所有后置处理器 包括自定义的******************
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
//***********************这里开始实例我们的配置类, 并开始循环调用beanFactory中所有的后置处理器,从而完成所有bean的注册、实例、及初始化
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
关于spring内置的后置处理器工作原理, 推荐以下博客
ConfigurationClassPostProcessor:https://blog.csdn.net/u010900754/article/details/99706436
AutowiredAnnotationBeanPostProcessor:
https://blog.csdn.net/qq_27529917/article/details/78454912
如有不实之处,还请各位大佬指点
最后
以上就是虚拟草丛为你收集整理的Spring基于注解式启动原理分析的全部内容,希望文章能够帮你解决Spring基于注解式启动原理分析所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复