当前位置 : 主页 > 编程语言 > java >

Spring5AOP——BeanPostProcessor

来源:互联网 收集:自由互联 发布时间:2023-02-04
什么是BeanPostProcessor? 有什么作用? Bean的后置处理器,首先来说,他是Spring中抽象出来的一个顶级的接口,他里面有如下两个方法。 /** * 允许对新的bean示例进行自定义的修改,例如检查

什么是BeanPostProcessor? 有什么作用?

Bean的后置处理器,首先来说,他是Spring中抽象出来的一个顶级的接口,他里面有如下两个方法。

/** * 允许对新的bean示例进行自定义的修改,例如检查标志接口或进行代理封装 * * spring上下文会在它的beng定义中自动检测BeanPostProcessor实例,并将它们应用于随后创建的每一个bean实例 * * implement {@link #postProcessAfterInitialization}. * 通常,通过实现BeanPostProcessor的postProcessBeforeInitialization方法(配合标记接口,如@Autowired)来填充bean实例, * 通过BeanPostProcessor的postProcessAfterInitialization方法进行bean实例的代理 * */ public interface BeanPostProcessor { /** * 在bean实例的初始化方法(例如InitializingBean的afterPropertiesSet或自定义的init-method)回调之前, * spring会应用此方法到bean实例上。一般用于bean实例的属性值的填充 */ @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * 在bean实例的初始化方法(例如InitializingBean的afterPropertiesSet或自定义的init-method)回调之后, * spring会应用此方法到bean实例上。 * 在有FactoryBean时,此方法会在FactoryBean实例与FactoryBean的目标对象创建时各调用一次 */ @Nullable default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }

简单点来理解,就是spring会自动从它的所有的bean定义中检测BeanPostProcessor类型的bean定义,然后实例化它们,再将它们应用于随后创建的每一个bean实例,在bean实例的初始化方法回调之前调用BeanPostProcessor的postProcessBeforeInitialization的方法(进行bean实例属性的填充),在bean实例的初始化方法回调之后调用BeanPostProcessor的postProcessAfterInitialization的方法(可以进行bean实例的代理封装)。

 

大家说它是Spring对外提供的拓展点,也许是因为,通过实现这个接口,程序员可以对Spring管理的bean的生命周期进行插手。

 

这也体现了AOP的设计思想,就比如在init()方法执行前后做出不同的动作,其实就是对bean的一种增强。

 

此外BeanPostProcessor可以存在多个。他们会被存储在一个列表中。然后依次被执行。

为什么要注册BeanPostProcessor?

所谓的注册,只不过是对当前上下文中所有的BeanPostProcessor进行一种集中式管理罢了,为什么非得这么做呢? 因为上下文中BeanPostProcessor的数量不是一成不变的,Spring为了启动的正常,需要添加原生的BeanPostProcessor,程序员因为自己的需求也会添加不同数量的bean的后置处理器,因此需要这种策略将上下文中所有的后置处理器进行统一的管理,方便回调。

BeanPostProcessor继承关系图

InstantiationAwareBeanPostProcessor

  • 在Bean的实例化过程中给Bean加上额外的逻辑
/** * 对象实例化前后以及实例化后设置propertyValues的回调 */ public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor { //用来在对象实例化前直接返回一个对象(如代理对象)来代替通过内置的实例化流程创建对象 @Nullable default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { return null; } //在对象实例化完毕执行populateBean之前 如果返回false则spring不再对对应的bean实例进行自动依赖注入 default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { return true; } //这里是在spring处理完默认的成员属性,应用到指定的bean之前进行回调,可以用来检查和修改属性,最终返回的PropertyValues会应用到bean中 //@Autowired、@Resource等就是根据这个回调来实现最终注入依赖的属性的。 @Nullable default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { return null; } //postProcessPropertyValues已经被标注@Deprecated,后续将会被postProcessProperties取代 @Deprecated @Nullable default PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { return pvs; } }

Spring中Bean的生命周期

Spring中Bean的生命周期

Spring作为一个优秀的框架,拥有良好的可扩展性。Spring对对象的可扩展性主要就是依靠InstantiationAwareBeanPostProcessor和BeanPostProcessor来实现的。

  • InstantiationAwareBeanPostProcessor:主要是作用于实例化阶段。
  • BeanPostProcessor:主要作用与初始化阶段。
public AnnotationConfigApplicationContext(Class<?>... componentClasses) { //调用默认无参构造器,主要初始化AnnotatedBeanDefinitionReader // 以及路径扫描器ClassPathBeanDefinitionScanner this(); //把传入的Class进行注册,Class既可以有@Configuration注解,也可以没有@Configuration注解 //如何注册委托给了 org.springframework.context.annotation.AnnotatedBeanDefinitionReader.register 方法进行注册 // 包装传入的Class 生成 BeanDefinition , 注册到BeanDefinitionRegistry register(componentClasses); refresh(); }

AnnotationConfigApplicationContext构造方法中调用refresh()方法

refresh() 方法中这里主要关心两个方法:

  • registerBeanPostProcessors(beanFactory):注册BeanPostProcessor
  • finishBeanFactoryInitialization(beanFactory):实例化余下的Singletions Bean

注册BeanPostProcessor

  • 注册拦截bean创建过程的BeanPostProcessor
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext { /** * BeanPostProcessor 的 bean,如果给出显式顺序,请按照顺序。 * 必须在应用程序bean的任何实例化之前调用。 * Instantiate and register all BeanPostProcessor beans, * respecting explicit order if given. * <p>Must be called before any instantiation of application beans. */ protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { // 1.注册BeanPostProcessor PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); } } final class PostProcessorRegistrationDelegate { public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { // 1.找出所有实现BeanPostProcessor接口的类 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. // 注册 BeanPostProcessorChecker // 主要用于记录一些 bean 的信息,这些 bean 不符合所有 BeanPostProcessors 处理的资格时 // BeanPostProcessor的目标计数 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; // 2.添加BeanPostProcessorChecker(主要用于记录信息)到beanFactory中 beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. // 区分 PriorityOrdered、Ordered 、以及非两者 // 3.定义不同的变量用于区分: 实现PriorityOrdered接口的BeanPostProcessor、实现Ordered接口的BeanPostProcessor、普通BeanPostProcessor // 3.1 priorityOrderedPostProcessors: 用于存放实现PriorityOrdered接口的BeanPostProcessor List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); // 3.2 internalPostProcessors: 用于存放Spring内部的BeanPostProcessor List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); // 3.3 orderedPostProcessorNames: 用于存放实现Ordered接口的BeanPostProcessor的beanName List<String> orderedPostProcessorNames = new ArrayList<>(); // 3.4 nonOrderedPostProcessorNames: 用于存放普通BeanPostProcessor的beanName List<String> nonOrderedPostProcessorNames = new ArrayList<>(); // 4.遍历postProcessorNames, 将BeanPostProcessors按3.1 - 3.4定义的变量区分开 for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 4.1 如果ppName对应的Bean实例实现了PriorityOrdered接口, 则拿到ppName对应的Bean实例并添加到priorityOrderedPostProcessors BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { // 4.2 如果ppName对应的Bean实例也实现了MergedBeanDefinitionPostProcessor接口, // 则将ppName对应的Bean实例添加到internalPostProcessors internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { // 4.3 如果ppName对应的Bean实例没有实现PriorityOrdered接口, 但是实现了Ordered接口, 则将ppName添加到orderedPostProcessorNames orderedPostProcessorNames.add(ppName); } else { // 4.4 否则, 将ppName添加到nonOrderedPostProcessorNames nonOrderedPostProcessorNames.add(ppName); } } // First, register the BeanPostProcessors that implement PriorityOrdered. // 5.首先, 注册实现PriorityOrdered接口的BeanPostProcessors // 5.1 对priorityOrderedPostProcessors进行排序 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); // 5.2 注册priorityOrderedPostProcessors registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. // 6.接下来, 注册实现Ordered接口的BeanPostProcessors List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String ppName : orderedPostProcessorNames) { // 6.1 拿到ppName对应的BeanPostProcessor实例对象 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); // 6.2 将ppName对应的BeanPostProcessor实例对象添加到orderedPostProcessors, 准备执行注册 orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { // 6.3 如果ppName对应的Bean实例也实现了MergedBeanDefinitionPostProcessor接口, // 则将ppName对应的Bean实例添加到internalPostProcessors internalPostProcessors.add(pp); } } // 6.4 对orderedPostProcessors进行排序 sortPostProcessors(orderedPostProcessors, beanFactory); // 6.5 注册orderedPostProcessors registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors. // 7.注册所有常规的BeanPostProcessors(过程与6类似) List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors. // 8.最后, 重新注册所有内部BeanPostProcessors(相当于内部的BeanPostProcessor会被移到处理器链的末尾) // 8.1 对internalPostProcessors进行排序 sortPostProcessors(internalPostProcessors, beanFactory); // 8.2注册internalPostProcessors registerBeanPostProcessors(beanFactory, internalPostProcessors); // Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // 重新注册用来自动探测内部ApplicationListener的postprocessor, // 这样可以将他们移到处理器链条的末尾 // 9.重新注册ApplicationListenerDetector(跟8类似,主要是为了移动到处理器链的末尾) beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); } }

通过beanFactory.getBeanNamesForType来获取所有BeanPostProcessor。

 

BeanPostProcessor按优先级分为PriorityOrdered,Ordered和其他的,对他们分别进行操作。

  • 先beanFactory.getBean进性实例化,
  • 再使用sortPostProcessors() 进行排序,
  • 最后registerBeanPostProcessors()进行注册。

BeanFactory.getBean()(注册Bean)

  • 拿到ppName对应的BeanPostProcessor实例对象
public interface BeanFactory { //根据bean的名字和class类型从容器中获取bean实例, // 增加类型校验进一步确保精准地获取到的实例 <T> T getBean(String name, Class<T> requiredType) throws BeansException; } public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory { @Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return doGetBean(name, requiredType, null, false); } protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { // 1.解析beanName,主要是解析别名、去掉FactoryBean的前缀“&” final String beanName = transformedBeanName(name); Object bean; // Eagerly check singleton cache for manually registered singletons. // 2.尝试从缓存中获取beanName对应的实例 Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { // 3.如果beanName的实例存在于缓存中 if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } // 3.1 返回beanName对应的实例对象(主要用于FactoryBean的特殊处理,普通Bean会直接返回sharedInstance本身) bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. // 4.scope为prototype的循环依赖校验:如果beanName已经正在创建Bean实例中,而此时我们又要再一次创建beanName的实例,则代表出现了循环依赖,需要抛出异常。 // 例子:如果存在A中有B的属性,B中有A的属性,那么当依赖注入的时候,就会产生当A还未创建完的时候因为对于B的创建再次返回创建A,造成循环依赖 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // Check if bean definition exists in this factory. // 5.获取parentBeanFactory BeanFactory parentBeanFactory = getParentBeanFactory(); // 5.1 如果parentBeanFactory存在,并且beanName在当前BeanFactory不存在Bean定义,则尝试从parentBeanFactory中获取bean实例 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. // 5.2 将别名解析成真正的beanName String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } // 5.3 尝试在parentBeanFactory中获取bean对象实例 else if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else if (requiredType != null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } } if (!typeCheckOnly) { // 6.如果不是仅仅做类型检测,而是创建bean实例,这里要将beanName放到alreadyCreated缓存 markBeanAsCreated(beanName); } try { // 7.根据beanName重新获取MergedBeanDefinition(步骤6将MergedBeanDefinition删除了,这边获取一个新的) final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // 7.1 检查MergedBeanDefinition checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. // 8.拿到当前bean依赖的bean名称集合,在实例化自己之前,需要先实例化自己依赖的bean String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { // 8.1 遍历当前bean依赖的bean名称集合 for (String dep : dependsOn) { // 8.2 检查dep是否依赖于beanName,即检查是否存在循环依赖 if (isDependent(beanName, dep)) { // 8.3 如果是循环依赖则抛异常 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } // 8.4 将dep和beanName的依赖关系注册到缓存中 registerDependentBean(dep, beanName); try { // 8.5 获取dep对应的bean实例,如果dep还没有创建bean实例,则创建dep的bean实例 getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } // Create bean instance. // 9.针对不同的scope进行bean的创建 if (mbd.isSingleton()) { // 9.1 scope为singleton的bean创建(新建了一个ObjectFactory,并且重写了getObject方法) sharedInstance = getSingleton(beanName, () -> { try { // 9.1.1 创建Bean实例 return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } }); // 9.1.2 返回beanName对应的实例对象 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. // 9.2 scope为prototype的bean创建 Object prototypeInstance = null; try { // 9.2.1 创建实例前的操作(将beanName保存到prototypesCurrentlyInCreation缓存中) beforePrototypeCreation(beanName); // 9.2.2 创建Bean实例 prototypeInstance = createBean(beanName, mbd, args); } finally { // 9.2.3 创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除) afterPrototypeCreation(beanName); } // 9.2.4 返回beanName对应的实例对象 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { // 9.3 其他scope的bean创建,可能是request之类的 // 9.3.1 根据scopeName,从缓存拿到scope实例 String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { // 9.3.2 其他scope的bean创建(新建了一个ObjectFactory,并且重写了getObject方法) Object scopedInstance = scope.get(beanName, () -> { // 9.3.3 创建实例前的操作(将beanName保存到prototypesCurrentlyInCreation缓存中) beforePrototypeCreation(beanName); try { // 9.3.4 创建bean实例 return createBean(beanName, mbd, args); } finally { // 9.3.5 创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除) afterPrototypeCreation(beanName); } }); // 9.3.6 返回beanName对应的实例对象 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { // 如果创建bean实例过程中出现异常,则将beanName从alreadyCreated缓存中移除 cleanupAfterBeanCreationFailure(beanName); throw ex; } } // Check if required type matches the type of the actual bean instance. // 10.检查所需类型是否与实际的bean对象的类型匹配 if (requiredType != null && !requiredType.isInstance(bean)) { try { // 10.1 类型不对,则尝试转换bean类型 T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return convertedBean; } catch (TypeMismatchException ex) { if (logger.isTraceEnabled()) { logger.trace("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } // 11.返回创建出来的bean实例对象 return (T) bean; } }
  • 先getSingleton()从缓存中获取Bean,如果没有则创建。
  • 创建过程先检查有无循环依赖,有则抛出异常。
  • 实例化bean前先实例化所依赖的对象。

createBean()

  • 创建Bean实例
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { @Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinition mbdToUse = mbd; // Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. //判断需要创建的Bean是否可以实例化,即是否可以通过当前的类加载器加载。 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { // 如果resolvedClass存在,并且mdb的beanClass类型不是Class,并且mdb的beanClass不为空(则代表beanClass存的是Class的name), // 则使用mdb深拷贝一个新的RootBeanDefinition副本,并且将解析的Class赋值给拷贝的RootBeanDefinition副本的beanClass属性, // 该拷贝副本取代mdb用于后续的操作 mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { // 2.验证及准备覆盖的方法(对override属性进行标记及验证) mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. // 3.实例化前的处理,给InstantiationAwareBeanPostProcessor一个机会返回代理对象来替代真正的bean实例,达到“短路”效果 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); // 4.如果bean不为空,则会跳过Spring默认的实例化过程,直接使用返回的bean if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { // 5.创建Bean实例(真正创建Bean的方法) Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } // 6.返回创建的Bean实例 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); } } }
  • 首先调用resolveBeanClass方法从BeanDefinition中解析出Bean对应的Class对象来。
  • 在doCreateBean() 之前调用resolveBeforeInstantiation() 方法,在resolveBeforeInstantiation()方法中如果容器有注册过InstantiationAwareBeanPostProcessor类型的后置处理器,如果有则挨个调用InstantiationAwareBeanPostProcessor后置处理类的postProcessBeforeInstantiation方法。
  • 如果postProcessBeforeInstantiation方法返回的结果不为null,则证明Bean的实例已经被自定义的后置处理器创建了,而后调用postProcessAfterInitialization方法对Bean做进一步的包装,接着不需要Spring进行后续的doCreateBean()逻辑创建bean实例,直接返回即可。

resolveBeforeInstantiation

  • 实例化前的处理,给InstantiationAwareBeanPostProcessor一个机会返回代理对象来替代真正的bean实例。
  • 如果bean不为空,则会跳过Spring默认的实例化过程,直接使用返回的bean。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { @Nullable protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { Object bean = null; if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { // Make sure bean class is actually resolved at this point. //1.mbd不是合成的,并且BeanFactory中存在InstantiationAwareBeanPostProcessor if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //2.解析beanName对应的Bean实例的类型 Class<?> targetType = determineTargetType(beanName, mbd); if (targetType != null) { //3.实例化前的后置处理器应用(处理InstantiationAwareBeanPostProcessor) bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null) { //4.如果返回的bean不为空,会跳过Spring默认的实例化过程 //所以只能在这里调用BeanPostProcessor实现类的PostProcessorsAfterInitialization方法 bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } //5.如果bean不为空,则将beforeInstantiationResolved赋值为true,代表在实例化之前已经解析 mbd.beforeInstantiationResolved = (bean != null); } return bean; } }

applyBeanPostProcessorsBeforeInstantiation

  • 实例化前的后置处理器应用(处理InstantiationAwareBeanPostProcessor)
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { @Nullable protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) { //1.遍历当前BeanFactory中的BeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { //2.应用InstantiationAwareBeanPostProcessor后置处理器,允许PostProcessorBeforeInstantiation方法返回bean对象的代理 if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //3.执行postProcessBeforeInstantiation方法,在Bean实例化前操作, //该方法可以返回一个构造完成的Bean实例,从而不会继续执行创建Bean实例的"正规流程",达到"短路"效果 Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); if (result != null) { //4.如果result不为null,也就是有后置处理器返回了bean实例对象,则会跳过Spring默认的实例化过程。 return result; } } } return null; } }

applyBeanPostProcessorsAfterInitialization

  • 如果返回的bean不为空,会跳过Spring默认的实例化过程,所以只能在这里调用BeanPostProcessor实现类的PostProcessorsAfterInitialization方法。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { @Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; // 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessAfterInitialization方法 for (BeanPostProcessor processor : getBeanPostProcessors()) { // 2.在bean初始化后,调用postProcessAfterInitialization方法 Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { // 3.如果返回null,则不会调用后续的BeanPostProcessors return result; } result = current; } return result; } }

InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法,该方法主要是在bean实例化之后,并且在其被设置上属性值之前去进行调用,用来判断是否继续去执行对属性赋值的流程,方法返回true,即默认情况下都会去执行populateBean方法,对Bean的属性进行赋值。

 

postProcessAfterInstantiation方法调用是在populateBean方法中,这里从doCreateBean方法进入。

doCreateBean() 创建bean

  • 创建Bean实例(真正创建Bean的方法)
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { // Instantiate the bean. // 1.新建Bean包装类 BeanWrapper instanceWrapper = null; //如果RootBeanDefinition是单例的,则移除未完成的FactoryBean实例的缓存 if (mbd.isSingleton()) { // 2.如果是FactoryBean,则需要先移除未完成的FactoryBean实例的缓存 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { // 3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args); } // 4.拿到创建好的Bean实例 final Object bean = instanceWrapper.getWrappedInstance(); // 5.拿到Bean实例的类型 Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { // 6.应用后置处理器MergedBeanDefinitionPostProcessor,允许修改MergedBeanDefinition, // Autowired注解、Value注解正是通过此方法实现注入类型的预解析 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. // 7.判断是否需要提早曝光实例:单例 && 允许循环依赖 && 当前bean正在创建中 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } // 8.提前曝光beanName的ObjectFactory,用于解决循环引用 // 8.1 应用后置处理器SmartInstantiationAwareBeanPostProcessor,允许返回指定bean的早期引用,若没有则直接返回bean addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. // 初始化bean实例。 Object exposedObject = bean; try { // 9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例 populateBean(beanName, mbd, instanceWrapper); // 10.对bean进行初始化 exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { // 11.如果允许提前曝光实例,则进行循环依赖检查 Object earlySingletonReference = getSingleton(beanName, false); // 11.1 earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空 if (earlySingletonReference != null) { if (exposedObject == bean) { // 11.2 如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用 exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { // 11.3 如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例 // && 当前bean有被其他bean依赖 // 11.4 拿到依赖当前bean的所有bean的beanName数组 String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { // 11.5 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { // 11.6 移除失败的添加到 actualDependentBeans actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { // 11.7 如果存在移除失败的,则抛出异常,因为存在bean依赖了“脏数据” throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try { // 12.注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } // 13.完成创建并返回 return exposedObject; } }

populateBean

  • 对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { // bw为空时的处理 if (bw == null) { // 如果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. // 如果bw为空,属性也为空,则跳过 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. // 给InstantiationAwareBeanPostProcessors最后一次机会在属性注入前修改Bean的属性值,也可以控制是否继续填充Bean // 具体通过调用postProcessAfterInstantiation方法,如果调用返回false,表示不必继续进行依赖注入,直接返回 // 主要是让用户可以自定义属性注入。比如用户实现一个 InstantiationAwareBeanPostProcessor 类型的后置处理器, // 并通过 postProcessAfterInstantiation 方法向 bean 的成员变量注入自定义的信息。 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { // 如果mbd不是合成的 && 存在InstantiationAwareBeanPostProcessor,则遍历处理InstantiationAwareBeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; // 在bean实例化后,属性填充之前被调用,允许修改bean的属性,如果返回false,则跳过之后的属性填充 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } // pvs是一个MutablePropertyValues实例,里面实现了PropertyValues接口, // 提供属性的读写操作实现,同时可以通过调用构造函数实现深拷贝 //获取BeanDefinition里面为Bean设置上的属性值 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 根据Bean配置的依赖注入方式完成注入,默认是0,即不走以下逻辑,所有的依赖注入都需要在xml文件中有显式的配置 // 如果设置了相关的依赖装配方式,会遍历Bean中的属性,根据类型或名称来完成相应注入,无需额外配置 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. // 根据beanName进行autowiring自动装配处理 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. //根据Bean的类型进行autowiring自动装配处理 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } //BeanFactory是否注册过InstantiationAwareBeanPostProcessors boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); //是否进行依赖检查,默认为false boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null; //注册过InstantiationAwareBeanPostProcessors 或者 需要依赖检查 if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } // 7.1 应用后置处理器InstantiationAwareBeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //在这里会对@Autowired标记的属性进行依赖注入 //调用AutowiredAnnotationBeanPostProcessor的postProcessProperties PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } // 对解析完但未设置的属性再进行处理 pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } } // 依赖检查,对应depend-on属性,3.0已经弃用此属性 if (needsDepCheck) { // 过滤出所有需要进行依赖检查的属性编辑器 if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } checkDependencies(beanName, mbd, filteredPds, pvs); } if (pvs != null) { //最终将属性注入到Bean的Wrapper实例里,这里的注入主要是供 //显式配置了autowiredbyName或者ByType的属性注入, //针对注解来讲,由于在AutowiredAnnotationBeanPostProcessor已经完成了注入, //所以此处不执行 applyPropertyValues(beanName, mbd, bw, pvs); } } }

在populateBean方法中,在对bean的属性进行真正赋值之前,会依次调用InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法。

InstantiationAwareBeanPostProcessor的postProcessProperties方法

  • 该方法主要是针对Bean的属性进行处理。
  • 该方法依然是在populateBean方法中被调用。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { ...... //BeanFactory是否注册过InstantiationAwareBeanPostProcessors boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); //是否进行依赖检查,默认为false boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null; //注册过InstantiationAwareBeanPostProcessors 或者 需要依赖检查 if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } // 7.1 应用后置处理器InstantiationAwareBeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //在这里会对@Autowired标记的属性进行依赖注入 //调用AutowiredAnnotationBeanPostProcessor的postProcessProperties PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } // 对解析完但未设置的属性再进行处理 pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } } ...... } }

跟进PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName)方法。

  • 该方法最终会调用InstantiationAwareBeanPostProcessor的实现类AutowiredAnnotationBeanPostProcessor类中的postProcessProperties方法。
  • 该方法主要是根据先前解析出来的Bean里面的被@Autowired标记的成员变量,将成员变量对应的Bean实例给自动注入到目标成员变量里,这样也就实现了依赖注入。
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware { @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { //获取指定类中@Autowired相关注解的元信息 InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); try { //对Bean的属性进行自动注入 metadata.inject(bean, beanName, pvs); } catch (BeanCreationException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex); } return pvs; } }

SmartInstantiationAwareBeanPostProcessor

  • 该类的方法主要是作用在Bean的实例化过程中的。
  • 主要供spring框架内部来使用
/** * 主要供spring框架内部来使用 */ public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor { //用来返回目标对象的最终类型(比如代理对象通过beanClass获取proxy type) @Nullable default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException { return null; } //提供一个拓展点用来解析获取用来实例化的构造器(比如未通过bean定义构造器以及参数的情况下,会根据这个回调来确定构造器) @Nullable default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException { return null; } //获取要提前暴露的bean的引用,用来支持单例对象的循环引用(一般是bean自身,如果是代理对象则需要取用代理引用) default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { return bean; } }

predictBeanType

  • 用来返回目标对象的最终类型(比如代理对象通过beanClass获取proxy type)
  • 该方法主要是在AbstractAutowireCapableBeanFactory类中的predictBeanType方法中调用。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { @Override @Nullable protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { // 1.拿到beanName的类型 Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch); // Apply SmartInstantiationAwareBeanPostProcessors to predict the // eventual type after a before-instantiation shortcut. // 2.应用SmartInstantiationAwareBeanPostProcessors后置处理器,来预测实例化的最终类型, // SmartInstantiationAwareBeanPostProcessors继承了InstantiationAwareBeanPostProcessor, // InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法可以改变Bean实例的类型, // 而SmartInstantiationAwareBeanPostProcessors的predictBeanType方法可以预测这个类型 if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { boolean matchingOnlyFactoryBean = typesToMatch.length == 1 && typesToMatch[0] == FactoryBean.class; for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; // 3.调用predictBeanType方法 Class<?> predicted = ibp.predictBeanType(targetType, beanName); if (predicted != null && (!matchingOnlyFactoryBean || FactoryBean.class.isAssignableFrom(predicted))) { // 4.如果predicted不为空 && (typesToMatch长度不为1 || typesToMatch[0]不为FactoryBean.class || // predicted是FactoryBean本身、子类或子接口),则返回predicted return predicted; } } } } // 5.否则返回beanName的类型 return targetType; } }

determineCandidateConstructors

  • 提供一个拓展点用来解析获取用来实例化的构造器(比如未通过bean定义构造器以及参数的情况下,会根据这个回调来确定构造器)
  • 该方法主要是在AbstractAutowireCapableBeanFactory类中的doCreateBean方法在执行createBeanInstance方法,去创建Bean实例,并返回包装类BeanWrapper的时候,调用Bean的构造函数创建Bean实例的时候被调用。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { ...... // Candidate constructors for autowiring? // 4.应用后置处理器SmartInstantiationAwareBeanPostProcessor,拿到bean的候选构造函数 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { // 5.如果ctors不为空 || mbd的注入方式为AUTOWIRE_CONSTRUCTOR || mdb定义了构造函数的参数值 || args不为空,则执行构造函数自动注入 return autowireConstructor(beanName, mbd, ctors, args); } // Preferred constructors for default construction? //默认构造的首选构造函数 ctors = mbd.getPreferredConstructors(); if (ctors != null) { return autowireConstructor(beanName, mbd, ctors, null); } // No special handling: simply use no-arg constructor. // 6.没有特殊处理,则使用默认的构造函数进行bean的实例化 return instantiateBean(beanName, mbd); } @Nullable protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) throws BeansException { if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) { //1.遍历所有的BeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; //2.调用SmartInstantiationAwareBeanPostProcessor的determineCandidateConstructors方法 //该方法可以返回要用于beanClass的候选构造函数 //例如:使用@Autowire注解修饰的构造函数,则该构造函数在这边会被AutowiredAnnotationBeanPostProcessor找到 Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); if (ctors != null) { return ctors; } } } } return null; } }

getEarlyBeanReference

  • 获取要提前暴露的bean的引用,用来支持单例对象的循环引用(一般是bean自身,如果是代理对象则需要取用代理引用)
  • 该方法也是在AbstractAutowireCapableBeanFactory类中的getEarlyBeanReference方法中被调用,而getEarlyBeanReference方法又被doCreateBean方法中的addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean))代码调用。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { Object exposedObject = bean; // 1.如果bean不为空 && mbd不是合成 && 存在InstantiationAwareBeanPostProcessors if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { // 2.应用所有SmartInstantiationAwareBeanPostProcessor,调用getEarlyBeanReference方法 if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; // 3.允许SmartInstantiationAwareBeanPostProcessor返回指定bean的早期引用 exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); } } } // 4.返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身 return exposedObject; } }

MergedBeanDefinitionPostProcessor

  • MergedBeanDefinitionPostProcessor接口中重要的方法只有一个,即postProcessMergedBeanDefinition。
//用来将merged BeanDefinition暴露出来 public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor { //在bean实例化完毕后调用 可以用来修改merged BeanDefinition的一些properties 或者用来给后续回调中缓存一些meta信息使用 //这个算是将merged BeanDefinition暴露出来的一个回调 //重点关注AutowiredAnnotationBeanPostProcessor,该类会把@Autowired等标记的 //需要依赖注入的成员变量或者方法实例给记录下来,方便后续populateBean使用 void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName); default void resetBeanDefinition(String beanName) { } }

postProcessMergedBeanDefinition

  • 该方法依然是在AbstractAutowireCapableBeanFactory类中的doCreateBean方法中被调用。
  • doCreateBean方法调用createBeanInstance用于创建bean实例并包装成包装类BeanWrapper,在createBeanInstance被调用之后,且在addSingletonFactory方法被调用之前被调用。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { ...... // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { // 6.应用后置处理器MergedBeanDefinitionPostProcessor,允许修改MergedBeanDefinition, // Autowired注解、Value注解正是通过此方法实现注入类型的预解析 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } ...... // 13.完成创建并返回 return exposedObject; } protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) { // 1.获取BeanFactory中已注册的BeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof MergedBeanDefinitionPostProcessor) { // 2.调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法 MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp; //重点关注AutowiredAnnotationBeanPostProcessor,该类会把@Autowired等标记的 //需要依赖注入的成员变量或者方法实例给记录下来,方便后续populateBean使用 bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName); } } } }

DestructionAwareBeanPostProcessor

  • 主要是用来对Bean的销毁做后置处理的
//处理对象销毁的前置回调 public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor { //这里实现销毁对象的逻辑 void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException; //判断是否需要处理这个对象的销毁 default boolean requiresDestruction(Object bean) { return true; } }

参考: https://segmentfault.com/a/1190000015830477

https://www.cnblogs.com/youzhibing/p/10559330.html

https://www.cnblogs.com/ZhuChangwu/p/11699677.html

上一篇:Spring5 AOP——@EnableAspectJAutoProxy
下一篇:没有了
网友评论