1. Spring Bean 元信息配置阶段
2. Spring Bean 元信息解析阶段
2.1 面向资源 BeanDefinition 解析
• BeanDefinitionReader
• XML 解析器 - BeanDefinitionParser
2.2 面向注解 BeanDefinition 解析
• AnnotatedBeanDefinitionReader#doRegisterBean
void doRegisterBean(Class<T> beanClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
// 实例化注解格式的Bean定义。其中包括设置bean的类型以及初始化用于获取类注解信息的元数据对象 生成普通的GenericBeanDefinition
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
/**
* 根据类上面的注解元数据信息,判断注册过程是否需要跳过当前的bean,如果配置类上面未标注@Conditional注解,会返回false。不会跳过
* conditionEvaluator默认实现类为ConditionEvaluator
* abd.getMetadata获取到的MedataData类型为 StandardAnnotationMetaData
*/
// 如果当前配置类上没有标注@Conditional注解,返回false
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
/***
// 1.supplier 使用:
Supplier<Integer> supplier = new Supplier<Integer>() {
@Override
public Integer get() {
return new Random().nextInt();
}
};
Integer result = supplier.get();
// 2. lambda表达式形式
supplier = () -> new Random().nextInt();
result = supplier.get();
*/
// 给Bean定义中注册回调supplier回调方法
abd.setInstanceSupplier(instanceSupplier);
// 默认实现类为:AnnotationScopeMetadataResolver,解析@Scope注解的元信息
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
// 设置bean的作用域,未设置默认为'singleton'
abd.setScope(scopeMetadata.getScopeName());
// 获取Bean的名称。如果传入的name为null。则使用默认的Bean Name生成器AnnotationBeanNameGenerator生成bean的名称.根据内省操作获取的bean名称.
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
// 解析公共注解上面的元数据信息 例如:@DependsOn, @Lazy,@Primary,@DependsOn,@Description
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
// 如果使用new AnnotationConfigApplicationContext(Class<?> clazz)创建的bean容器,
// 则此处的qualifiers和下面的definitionCustomizers都默认为null
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
// 用来保存Bean的定义。包括bean的名称,定义及别名信息
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
// 设置bean定义的作用域模式,如果为ScopedProxyMode.NO,直接返回.
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 真正完成配置类bean定义的注册。将bean定义注册到bean定义注册中心,即:BeanDefinitionRegistry中
// this.registry即AnnotationConfigApplicationContext对象
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
3. Spring Bean 注册阶段
DefaultListableBeanFactory#registerBeanDefinition
/**
* 注册BeanDefinition
* @param beanName bean的名称
* @param beanDefinition bean的定义
* @throws BeanDefinitionStoreException
*/
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
// 从beanDefinitionMap中根据bean名称获取Bean定义,第一次获取到的是null
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
else if (existingDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (logger.isInfoEnabled()) {
logger.info("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
existingDefinition + "] with [" + beanDefinition + "]");
}
}
else if (!beanDefinition.equals(existingDefinition)) {
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
// 注册
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
// 判断bean的创建是否已经开始
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
removeManualSingletonName(beanName);
}
}
else {
// 如果正处于bean定义的注册阶段,直接将bean定义放入到bean定义的map集合中.
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
// 将bean的名称保存到Bean定义名称的集合中 使用arraylist 保证注入有序
this.beanDefinitionNames.add(beanName);
removeManualSingletonName(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
4. Spring BeanDefinition 合并阶段
合并发生在getBean时期 之前的BeanDefinition注册生成的是GenericBeanDefinition
4.1准备Demo
/**
* BeanDefinition 合并示例
* 普通Bean实例 不需要合并
* @see org.springframework.beans.factory.support.RootBeanDefinition
* 构建Bean{@link org.springframework.beans.factory.support.BeanDefinitionBuilder#rootBeanDefinition(Class)}
*
* 一般的Bean定义 无parent 和RootBeandiftion 一样
* @see org.springframework.beans.factory.support.GenericBeanDefinition
*
* 合并Bean
* {@link ConfigurableBeanFactory#getMergedBeanDefinition(String)}
* {@link org.springframework.beans.factory.support.AbstractBeanFactory#getMergedBeanDefinition(String, BeanDefinition, BeanDefinition)}
* @since
*/
public class MergedBeanDefinitionDemo {
public static void main(String[] args) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// 基于 XML 资源 BeanDefinitionReader 实现
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
String location = "META-INF/dependency-lookup-context.xml";
// 基于 ClassPath 加载 XML 资源
Resource resource = new ClassPathResource(location);
// 指定字符编码 UTF-8
EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
int beanNumbers = beanDefinitionReader.loadBeanDefinitions(encodedResource);
System.out.println("已加载 BeanDefinition 数量:" + beanNumbers);
// 通过 Bean Id 和类型进行依赖查找
User user = beanFactory.getBean("user", User.class);
System.out.println(user);
User superUser = beanFactory.getBean("superUser", User.class);
System.out.println(superUser);
}
}
4.2核心源码
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {
// 加同步锁,然后进行操作.
synchronized (this.mergedBeanDefinitions) {
// 用于存放返回结果.
RootBeanDefinition mbd = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
// 检查beanName对应的MergedBeanDefinition是否存在于缓存中.
mbd = this.mergedBeanDefinitions.get(beanName);
}
// 如果beanName对应的BeanDefinition不在缓存中时
if (mbd == null) {
if (bd.getParentName() == null) {
// 如果bd的parentName为空,表示bd没有父定义,不需要与父定义进行合并操作.即:bd的MergedBeanDefinition就是bd自己
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition) {
// 如果bd的类型为RootBeanDefinition,则bd的MergedBeanDefinition就是bd自己,直接克隆一个副本
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
// 否则使用bd构建一个RootBeanDefinition.
// 一般情况下,BeanDefinition在被加载之后是GenericBeanDefinition(xml) 或者 ScannedGenericBeanDefinition(注解) 是GenericBeanDefinition ->RootBeanDefinition
mbd = new RootBeanDefinition(bd);
}
}
else {
// Child bean definition: needs to be merged with parent.
// 否则,bd存在着父定义,需要和父定义合并.
BeanDefinition pbd;
try {
// 获取父定义的BeanName.
String parentBeanName = transformedBeanName(bd.getParentName());
// 如果父定义的beanName和当前bean的beanName不同
if (!beanName.equals(parentBeanName)) {
// 则获取父定义的MergedBeanDefinition(也就是bd的爷爷定义...)
/**
* 一般情况下,Spring 通过反射机制利用 bean 的 class 属性指定实现类来实例化 bean。
* 而 FactoryBean 是一种特殊的 bean,它是个工厂 bean,可以自己创建 bean 实例,如果一个类实现了 FactoryBean 接口,
* 则该类可以自己定义创建实例对象的方法,只需要实现它的 getObject() 方法。
*
* 很多中间件都利用 FactoryBean 来进行扩展。例如:
*
* public class AppleFactoryBean implements FactoryBean<Apple> {
@Override
public Apple getObject() throws Exception {
Apple apple = new Apple();
apple.setName("bigApple");
return apple;
}
@Override
public Class<?> getObjectType() {
return Apple.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
注意:
为了区分 “FactoryBean” 和 “FactoryBean 创建的 bean 实例”,Spring 使用了 “&” 前缀。假设我们的 beanName 为 apple,
则 getBean("apple") 获得的是 AppleFactoryBean 通过 getObject() 方法创建的 bean 实例;
而 getBean("&apple") 获得的是 AppleFactoryBean 本身。
*
*/
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
// 如果父定义的beanName和bd的beanName相同,则拿到父亲的BeanFactory
// 只有存在父BeanFactory的情况下,才允许父定义beanName与自己相同,否则就是将自己设置为父定义.
BeanFactory parent = getParentBeanFactory();
// 如果父BeanFactory是ConfigurableBeanFactory,则通过BeanFactory获取父定义的MergedBeanDefinition.
if (parent instanceof ConfigurableBeanFactory) {
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
}
else {
// 否则抛出异常.
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without an AbstractBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
// 使用父定义pbd构建一个新的RootBeanDefinition对象(通过深拷贝)
mbd = new RootBeanDefinition(pbd);
// 然后使用bd覆盖父定义.
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
// 如果没有设置Scope属性,默认设置为singleton.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
// 如果containingBd不为空 && 不是单实例的 && mbd为单实例,则将mbd的scope属性设置为containingBd的scope属性.
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
// 如果containingBd为空,而且设置了缓存Bean的元数据,则将beanName和mbd放入到beanDefinition的缓存中,便于以后可以直接取出使用.
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
return mbd;
}
}
5. Spring Bean Class 加载阶段
6. Spring Bean 实例化前阶段
- Demo
/**
* Spring Bean 实例化前阶段
* - 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation(String, RootBeanDefinition)}
* - 依赖
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(Class, String)} }
*
*
* @since
*/
class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (ObjectUtils.nullSafeEquals("superUser", beanName) && SuperUser.class.equals(beanClass)) {
// 把配置完成 superUser Bean 覆盖
return new SuperUser();
}
return null; // 保持 Spring IoC 容器的实例化操作
}
非主流生命周期 - Bean 实例化前阶段
• InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiati
/**
* 创建creatBean
*
* 如果需要使用postProcessor 生成代理对象{@link AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation}
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* @see #doCreateBean
*/
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
// 获取bean的定义信息
RootBeanDefinition mbdToUse = mbd;
// 解析bean的类型,使用类加载器真实加载Bean的Class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
// 对lookup-method和replaced-method指定的方法进行预处理.
// 主要是标记bean中是否有重载方法。如果一个类有多个重载方法,在后面真正调用或者增强的时候,还需要根据参数类型和参数个数判断调用的哪一个方法,
// 此处相当于是提前处理。对于只有一个方法的bean,直接标记为无重载方法.
// 使用的地方:该处设置完标志位之后,在后期的实例化过程中使用cglib实例化策略的时候会使用到。
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 在真正创建Bean之前,执行bean实例化之前的一些工作,可以在此处生成自定义的代理对象.
// 通过实现InstantiationAwareBeanPostProcessor接口来进行自定义扩展,生成自定义的代理对象
// 可参考:【示例代码:com.wb.spring.instantiationaware.MyInstantiationAwareBeanPostProcessor】
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
// 执行创建Bean的操作
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
7. Spring Bean 实例化阶段
Demo
/**
* 6.Spring Bean 实例化前阶段
* - 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation(String, RootBeanDefinition)}
* - 依赖
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(Class, String)} }
* 7. SpringBean 实例化阶段
* - 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance(String, RootBeanDefinition, Object[])}
* - 实现方式 实例化策略实例化
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean(String, RootBeanDefinition)}
* - 构造器依赖注入
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireConstructor(String, RootBeanDefinition, Constructor[], Object[])}
*
* @since
*/
class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (ObjectUtils.nullSafeEquals("superUser", beanName) && SuperUser.class.equals(beanClass)) {
// 把配置完成 superUser Bean 覆盖
return new SuperUser();
}
return null; // 保持 Spring IoC 容器的实例化操作
}
}
- 传统实例化方式
实例化策略 - InstantiationStrategy - 构造器依赖注入
/**
* 实例化对象
* Create a new instance for the specified bean, using an appropriate instantiation strategy:
* factory method, constructor autowiring, or simple instantiation.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation 有参构造器
* @return a BeanWrapper for the new instance
* @see #obtainFromSupplier
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
* @see #instantiateBean
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 解析Bean的Class类型
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 如果Bean不是public,而且是不允许共有权限访问,直接抛出异常.
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
/**
* 通过指定的回调方法去创建bean实例,Spring5.0版本之后新增的方法。
* 可以通过实现BeanFactoryPostProcessor接口来进行扩展,设置自定义的Supplier,通过自定义supplier实例化对象
*/
// 可参考:【示例代码:com.wb.spring.supplier.SupplierBeanFactoryPostProcessor】
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
/**
* 如果当前bean指定了对应的工厂方法,则通过工厂方法去创建bean实例
* 底层会获取工厂方法【静态工厂方法|实例化方法】--> 然后解析方法入参 --> 然后执行反射调用创建实例 --> 封装为包装对象返回.
*
* fixme: 该方法的实现特别长 230行左右的代码
*/
if (mbd.getFactoryMethodName() != null) {
// 通过工厂方法创建实例,可参考:【示例代码:com.wb.spring.factorymethod.InstanceFactoryMethod,com.wb.spring.factorymethod.StaticFactoryMethod】
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
// 原型(prototype),多次获取的时候会走该分支
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 因为一个类可能由多个构造函数,所以需要根据配置文件中配置的参数或传入的参数来确定最终调用的构造函数。
// 因为判断过程会比较,所以spring会将解析、确定好的构造函数缓存到BeanDefinition中的resolvedConstructorOrFactoryMethod字段中。
// 在下次创建相同时直接从RootBeanDefinition中的属性resolvedConstructorOrFactoryMethod缓存的值获取,避免再次解析
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
// 表示构造函数的参数是否已经解析妥当
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
//
if (autowireNecessary) {
// 则通过构造函数完成实例的创建
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认的bean对象创建策略进行bean对象的创建 ***【此处使用了策略设计模式】***
return instantiateBean(beanName, mbd);
}
}
/** 象的构造函数 */
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
// 获取到了构造函数 || 注入模式为使用构造函数 || bean定义中指定了带参数的构造函数 || 创建bean对象时的入参args[参数列表对应的值列表]不为null
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 使用构造函数及入参进行bean对象的创建
return autowireConstructor(beanName, mbd, ctors, args);
}
/** 获取指定的用来创建bean对象的默认构造函数 */
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
/**
* 如果上述情况都没有:没有创建bean的回调方法 && 没有工厂方法 && 构造函数的参数未解析完毕 && 没有预先指定的默认构造函数
* 则使用默认策略来创建bean对象
*/
return instantiateBean(beanName, mbd);
}
8. Spring Bean 实例化后阶段
- Bean 属性赋值( Populate) 判断
InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation]
作用判断当前类是否要进行赋值 如果return false 则不需要赋值
Demo
/**
* 6.Spring Bean 实例化前阶段
* - 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation(String, RootBeanDefinition)}
* - 依赖
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(Class, String)} }
* 7. SpringBean 实例化阶段
* - 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance(String, RootBeanDefinition, Object[])}
* - 实现方式 实例化策略实例化
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean(String, RootBeanDefinition)}
* - 构造器依赖注入
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireConstructor(String, RootBeanDefinition, Constructor[], Object[])}
*8. Spring Bean 实例化后阶段
* 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean(String, RootBeanDefinition, BeanWrapper)}
* {@link InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation(Object, String)}
* @since 2022/04/21
*/
class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (ObjectUtils.nullSafeEquals("superUser", beanName) && SuperUser.class.equals(beanClass)) {
// 把配置完成 superUser Bean 覆盖
return new SuperUser();
}
return null; // 保持 Spring IoC 容器的实例化操作
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if (ObjectUtils.nullSafeEquals("user", beanName) && User.class.equals(bean.getClass())) {
User user = (User) bean;
user.setId(2L);
user.setName("mercyblitz");
// "user" 对象不允许属性赋值(填入)(配置元信息 -> 属性值)
return false;
}
return true;
}
}
9. Spring Bean 属性赋值前阶段
- Bean 属性值元信息
PropertyValues - Bean 属性赋值前回调
• Spring 1.2 - 5.0: InstantiationAwareBeanPostProcessor#postProcessPropertyValues
• Spring 5.1: InstantiationAwareBeanPostProcessor#postProcessProperties
9.1 Demo
/**
* 6.Spring Bean 实例化前阶段
* - 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation(String, RootBeanDefinition)}
* - 依赖
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(Class, String)} }
* 7. SpringBean 实例化阶段
* - 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance(String, RootBeanDefinition, Object[])}
* - 实现方式 实例化策略实例化
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean(String, RootBeanDefinition)}
* - 构造器依赖注入
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireConstructor(String, RootBeanDefinition, Constructor[], Object[])}
*8. Spring Bean 实例化后阶段
* 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean(String, RootBeanDefinition, BeanWrapper)}
* 核心类 {@link InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation(Object, String)}
* 9. Spring Bean 属性赋值前阶段
* 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean(String, RootBeanDefinition, BeanWrapper)}
* 核心类
* {@link InstantiationAwareBeanPostProcessor#postProcessProperties(PropertyValues, Object, String)}
* @since 2022/04/21
*/
class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (ObjectUtils.nullSafeEquals("superUser", beanName) && SuperUser.class.equals(beanClass)) {
// 把配置完成 superUser Bean 覆盖
return new SuperUser();
}
return null; // 保持 Spring IoC 容器的实例化操作
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if (ObjectUtils.nullSafeEquals("user", beanName) && User.class.equals(bean.getClass())) {
User user = (User) bean;
user.setId(2L);
user.setName("mercyblitz");
// "user" 对象不允许属性赋值(填入)(配置元信息 -> 属性值)
return false;
}
return true;
}
// user 是跳过 Bean 属性赋值(填入)
// superUser 也是完全跳过 Bean 实例化(Bean 属性赋值(填入))
// userHolder
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
// 对 "userHolder" Bean 进行拦截
if (ObjectUtils.nullSafeEquals("userHolder", beanName) && UserHolder.class.equals(bean.getClass())) {
// 假设 <property name="number" value="1" /> 配置的话,那么在 PropertyValues 就包含一个 PropertyValue(number=1)
final MutablePropertyValues propertyValues;
if (pvs instanceof MutablePropertyValues) {
propertyValues = (MutablePropertyValues) pvs;
} else {
propertyValues = new MutablePropertyValues();
}
// 等价于 <property name="number" value="1" />
propertyValues.addPropertyValue("number", "1");
// 原始配置 <property name="description" value="The user holder" />
// 如果存在 "description" 属性配置的话
if (propertyValues.contains("description")) {
// PropertyValue value 是不可变的
// PropertyValue propertyValue = propertyValues.getPropertyValue("description");
propertyValues.removePropertyValue("description");
propertyValues.addPropertyValue("description", "The user holder V2");
}
return propertyValues;
}
return null;
}
9.2属性填充
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
// 是否需要继续进行属性填充.
boolean continueWithPropertyPopulation = true;
/**
* 首先判断bean在初始化的时候是否需要进行属性值的注入.
*
* 可以通过扩展InstantiationAwareBeanPostProcessor接口来实现是否进行属性值注入的判断逻辑。
* 如下,直接返回false,则所有标注@Autowired注解的都不会进行依赖注入
*
* @Component
* class MyProcessor implements InstantiationAwareBeanPostProcessor {
* @Override
* public boolean (Object bean, String beanName) {
* return false;
* }
* }
*/
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
// 如果不需要进行属性的依赖注入,则直接返回.
if (!continueWithPropertyPopulation) {
return;
}
/** 获取当前正在实例化的bean的所有属性及值,类型为map: key:属性名称,value:值或者引用 配置的对象属性 */
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
/** 如果bean定义中指定的注入类型为通过名称或者通过类型注入,则解析出依赖的属性值或引用。但是该步骤不会进行属性的赋值操作 */
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
/** 如果是按照名称进行自动注入,通过属性名称获取依赖的属性值或者引用 */
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
// TODO WangBing ???
autowireByName(beanName, mbd, bw, newPvs);
}
/** 如果是按照类型进行自动注入,则通过属性的类型获取依赖的属性值或者引用 */
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
// TODO WangBing ???
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 当前bean是否有InstantiationAwareBeanPostProcessor类型的后置处理器
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 自动装配时需要进行依赖的检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
// 如果存在着InstantiationAwareBeanPostProcessor【继承自BeanPostProcessor】类型的后置处理器
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果是InstantiationAwareBeanPostProcessor的实例
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 则依次执行后置处理器的postProcessProperties,首先使用postProcessProperties,获取属性值
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 如果通过postProcessProperties未获取到属性值,再通过postProcessPropertyValues获取属性值
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
// 如果需要进行依赖的检查【包括简单类型和对象类型】
if (needsDepCheck) {
if (filteredPds == null) {
/**
* 通过一些过滤条件过滤掉不需要自动注入属性值的属性
* 其中包括:refresh()方法的prepareBeanFactory步骤中所忽略的接口.
*/
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
/**
* 检查属性值的依赖。如果bean中的属性有setter方法,但是属性名称没有包含在属性值列表中,将会抛出异常
*/
checkDependencies(beanName, mbd, filteredPds, pvs);
}
/** 如果解析出来的依赖属性值集合不为空,则通过applyPropertyValues进行属性值的填充 */
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
10. Spring Bean Aware接口回调阶段
- Spring Aware 接口
• BeanNameAware
• BeanClassLoaderAware
• BeanFactoryAware
• EnvironmentAware
• EmbeddedValueResolverAware
• ResourceLoaderAware
• ApplicationEventPublisherAware
• MessageSourceAware
• ApplicationContextAware
/**
* 10. Spring Bean Aware接口回调阶段
* 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(String, Object, RootBeanDefinition)}
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods(String, Object)}
* 依赖
* {@link BeanNameAware#setBeanName(String)}
* {@link BeanClassLoaderAware#setBeanClassLoader(ClassLoader)}
* {@link BeanFactoryAware#setBeanFactory(BeanFactory)}
* {@link EnvironmentAware#setEnvironment(Environment)}
* @since
*/
public class UserHolder implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, EnvironmentAware {
private final User user;
private Integer number;
private String description;
private ClassLoader classLoader;
private BeanFactory beanFactory;
private String beanName;
private Environment environment;
public UserHolder(User user) {
this.user = user;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
11. Spring Bean 初始化前阶段
- 已完成
• Bean 实例化
• Bean 属性赋值 - Bean Aware 接口回调
• 方法回调
• BeanPostProcessor#postProcessBeforeInitialization
11.1 Demo
11.2 源码
/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
* <p>Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @return the initialized bean instance (potentially wrapped)
* @see BeanNameAware
* @see BeanClassLoaderAware
* @see BeanFactoryAware
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #invokeInitMethods
* @see #applyBeanPostProcessorsAfterInitialization
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
/**
* 执行Aware 接口回调
* 调用Bean实现的Aware接口的方法,主要包括下面三个接口
* BeanNameAware ----> setBeanName()
* BeanClassLoaderAware ----> setBeanClassLoader()
* BeanFactoryAware ----> setBeanFactory()
*/
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
/** 调用Bean对象的postProcessBeforeInitialization方法,此处会执行标注@PostConstruct注解的方法 */
// 此处会调用ApplicationContextAwareProcessor执行其他的aware方法.
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
/**
* 执行Bean的初始化方法:
*
* 1.先判断Bean是否实现了InitializingBean接口,如果实现了InitializingBean接口,则调用Bean对象的afterPropertiesSet方法;
* 2.然后判断Bean是否有指定init-method方法,如果指定了init-method方法,则调用bean对象的init-method指定的方法.
*/
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
/**
* 调用Bean对象的postProcessAfterInitialization方法
*
* 如果需要创建代理,在该步骤中执行postProcessAfterInitialization方法的时候会去创建代理
* 调用AbstractAutoProxyCreator类的postProcessAfterInitialization方法,然后调用wrapIfNecessary方法去创建代理.
*
*
* 另外还有一些Aware接口,也会在该步骤中执行,例如:ApplicationContextAwareProcessor后置处理器,对应的setApplicationContext方法会被执行.
*/
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
12. Spring Bean 初始化阶段
- @PostConstruct 标注方法
- 实现 InitializingBean 接口的 afterPropertiesSet() 方法
- 自定义初始化方法
/**
* 10. Spring Bean Aware接口回调阶段
* 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(String, Object, RootBeanDefinition)}
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods(String, Object)}
* 依赖
* {@link BeanNameAware#setBeanName(String)}
* {@link BeanClassLoaderAware#setBeanClassLoader(ClassLoader)}
* {@link BeanFactoryAware#setBeanFactory(BeanFactory)}
* {@link EnvironmentAware#setEnvironment(Environment)}
*
* 12 SpringBean 初始化
* 12.1 @PostConstruct
* 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(Object, String)}
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization(Object, String)}
* 核心类 {@link org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#postProcessBeforeInitialization(Object, String)}
*
* 12.2 InitializingBean
* 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods(String, Object, RootBeanDefinition)}
* 核心类
* {@link InitializingBean#afterPropertiesSet()} }
* 12.1 自定义方法
* 入口
* {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods(String, Object, RootBeanDefinition)}
*
* @since
*/
public class UserHolder implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, EnvironmentAware,InitializingBean{
private final User user;
private Integer number;
private String description;
private ClassLoader classLoader;
private BeanFactory beanFactory;
private String beanName;
private Environment environment;
public UserHolder(User user) {
this.user = user;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@PostConstruct
public void initPostConstruct() {
// postProcessBeforeInitialization V3 -> initPostConstruct V4
this.description = "The user holder V4";
System.out.println("initPostConstruct() = " + description);
}
@Override
public void afterPropertiesSet() throws Exception {
// initPostConstruct V4 -> afterPropertiesSet V5
this.description = "The user holder V5";
System.out.println("afterPropertiesSet() = " + description);
}
public void init() {
// initPostConstruct V5 -> afterPropertiesSet V6
this.description = "The user holder V6";
System.out.println("init() = " + description);
}
public void doDestroy() {
// destroy : The user holder V11
this.description = "The user holder V12";
System.out.println("doDestroy() = " + description);
}
13. Spring Bean 初始化后阶段
- BeanPostProcessor#postProcessAfterInitialization
14. Spring Bean 初始化完成阶段
方法回调
• Spring 4.1 +: SmartInitializingSingleton#afterSingletonsInstantiated
15. Spring Bean 销毁前阶段
方法回调
• Spring 4.1 +: SmartInitializingSingleton#afterSingletonsInstantiated
16. Spring Bean 销毁阶段
Bean 销毁( Destroy)
• @PreDestroy 标注方法
• 实现 DisposableBean 接口的 destroy() 方法
• 自定义销毁方法
17. Spring Bean 垃圾收集
Bean 垃圾回收( GC)
• 关闭 Spring 容器( 应用上下文)
• 执行 GC
• Spring Bean 覆盖的 finalize() 方法被回调