欢迎访问Spring Cloud中国社区

《重新定义Spring Cloud实战》由Spring Cloud中国社区倾力打造,基于Spring Cloud的Finchley.RELEASE版本,本书内容宽度足够广、深度足够深,而且立足于生产实践,直接从生产实践出发,包含大量生产实践的配置。欢迎加微信Software_King进群答疑,国内谁在使用Spring Cloud?欢迎登记

SpringBoot2 | Spring IOC 流程中核心扩展接口的12个扩展点(十一)

张书康 · 10月前 · 2047 ·

微信公众号:吉姆餐厅ak
学习更多源码知识,欢迎关注。
在这里插入图片描述


SpringBoot2 | SpringBoot启动流程源码分析(一)

SpringBoot2 | SpringBoot启动流程源码分析(二)

SpringBoot2 | @SpringBootApplication注解 自动化配置流程源码分析(三)

SpringBoot2 | SpringBoot Environment源码分析(四)

SpringBoot2 | SpringBoot自定义AutoConfiguration | SpringBoot自定义starter(五)

SpringBoot2 | SpringBoot监听器源码分析 | 自定义ApplicationListener(六)

SpringBoot2 | 条件注解@ConditionalOnBean原理源码深度解析(七)

SpringBoot2 | Spring AOP 原理源码深度剖析(八)

SpringBoot2 | SpingBoot FilterRegistrationBean 注册组件 | FilterChain 责任链源码分析(九)

SpringBoot2 | BeanDefinition 注册核心类 ImportBeanDefinitionRegistrar (十)

SpringBoot2 | Spring 核心扩展接口 | 核心扩展方法总结(十一)


概述

Spring 的核心思想即是容器。整个容器 refresh 时,外部看似风平浪静,内部实则一片汪洋大海。另外整个流程严格遵守开闭原则,内部对修改关闭,对扩展开放。

可以这么理解:
把 Spring 容器理解为一个钥匙环,上面挂满了钥匙,每个钥匙理解为一个扩展接口。钥匙的顺序是固定的,可理解为接口的调用顺序固定,对修改关闭。每个钥匙可以用来做不同的事情,可理解为扩展接口的不同实现,对扩展开放。

Spring 提供了各种丰富的扩展接口,本篇主要对 IOC 过程中涉及的扩展接口做个整理。

对应的 UML 如下:

在这里插入图片描述

调用顺序如下:

分别来看。


1。BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry

BeanDefinitionRegistryPostProcessor接口在读取项目中的beanDefinition之后执行,提供的一个补充扩展接口,
用来动态注册beanDefinition。调用点:
PostProcessorRegistrationDelegate中:

  1. if (beanFactory instanceof BeanDefinitionRegistry) {
  2. //......
  3. // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
  4. boolean reiterate = true;
  5. while (reiterate) {
  6. reiterate = false;
  7. //获取所有的 BeanDefinitionRegistryPostProcessor 类型的bean
  8. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  9. for (String ppName : postProcessorNames) {
  10. if (!processedBeans.contains(ppName)) {
  11. //通过 getBean 方法进行实例化
  12. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  13. processedBeans.add(ppName);
  14. reiterate = true;
  15. }
  16. }
  17. sortPostProcessors(currentRegistryProcessors, beanFactory);
  18. registryProcessors.addAll(currentRegistryProcessors);
  19. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  20. currentRegistryProcessors.clear();
  21. }
  22. //......
  23. }

示例:手动注册BeanDefinition::

  1. @Component
  2. public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
  3. @Override
  4. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  5. System.out.println("postProcessBeanDefinitionRegistry ...");
  6. //手动注册 beanDefinition
  7. registry.registerBeanDefinition("myBeanDefinitionRegistrar",new AnnotatedGenericBeanDefinition(MyBeanDefinitionRegistrar.class));
  8. }
  9. }

2 。BeanFactoryPostProcessor.postProcessBeanFactory

BeanFactoryPostProcessorBeanPostProcessor 接口比较相似,从字面不难看出,前者多了一个 factory,所以该接口正是beanFactory的扩展接口,使用场景:一般用来在读取所有的beanDefinition信息之后,实例化之前,通过该接口可进一步自行处理,比如修改beanDefinition等。调用点在上面第一个扩展接口之后,也在PostProcessorRegistrationDelegate中:

  1. if (beanFactory instanceof BeanDefinitionRegistry) {
  2. //......
  3. // Do not initialize FactoryBeans here: We need to leave all regular beans
  4. // 获取所有的 BeanFactoryPostProcessor 类型
  5. String[] postProcessorNames =
  6. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
  7. // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  8. // Ordered, and the rest.
  9. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  10. List<String> orderedPostProcessorNames = new ArrayList<>();
  11. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  12. for (String ppName : postProcessorNames) {
  13. if (processedBeans.contains(ppName)) {
  14. // skip - already processed in first phase above
  15. }
  16. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  17. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  18. }
  19. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  20. orderedPostProcessorNames.add(ppName);
  21. }
  22. else {
  23. nonOrderedPostProcessorNames.add(ppName);
  24. }
  25. }
  26. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  27. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  28. //执行所有的 BeanFactoryPostProcessor 实现逻辑
  29. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  30. //......
  31. }

示例:动态修改BeanDefinition

  1. @Component
  2. public class MyBeanDefinitionRegistryPostProcessor implements BeanFactoryPostProcessor {
  3. @Override
  4. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  5. BeanDefinition myBeanDefinitionRegistrar = beanFactory.getBeanDefinition("myBeanDefinitionRegistrar");
  6. //可以修改 beanDefinition 信息。这里将bean 设置为单例
  7. myBeanDefinitionRegistrar.setScope(BeanDefinition.SCOPE_SINGLETON);
  8. }
  9. }

3。InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation

Instantiation 实例化的意思,和Initialization初始化 比较相似,容易混淆。
postProcessBeforeInstantiation用来获取 bean,如果获取到,则不再执行对应 bean的初始化之前流程,直接执行后面要讲的postProcessAfterInitialization方法。
调用点在AbstractAutowireCapableBeanFactory中:

  1. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException {
  3. //......
  4. try {
  5. //执行实例化之前的方法
  6. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  7. if (bean != null) {
  8. return bean;
  9. }
  10. }
  11. catch (Throwable ex) {
  12. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  13. "BeanPostProcessor before instantiation of bean failed", ex);
  14. }
  15. //......
  16. }
  1. protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
  2. Object bean = null;
  3. if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
  4. // Make sure bean class is actually resolved at this point.
  5. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  6. Class<?> targetType = determineTargetType(beanName, mbd);
  7. if (targetType != null) {
  8. //开始执行 postProcessBeforeInstantiation 方法
  9. bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
  10. //如果获得结果不为空,则直接执行实例化之后的扩展接口。结束 bean 实例化流程。
  11. if (bean != null) {
  12. bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
  13. }
  14. }
  15. }
  16. mbd.beforeInstantiationResolved = (bean != null);
  17. }
  18. return bean;
  19. }

如果postProcessBeforeInstantiation获得结果不为空,则结束 bean 实例化流程。


4。SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors

该扩展点决定判断合适的 bean 构造方法。
具体可参考AutowiredAnnotationBeanPostProcessor实现类,针对以下使用场景:
MyComponent1中通过构造方法注入MyComponent2:

  1. @Autowired
  2. public MyComponent(MyComponent2 component2){
  3. System.out.println("myComponent init...");
  4. }

这里会判断选择出合适的构造方法,并实例化需要的参数 bean。
调用点在AbstractAutowireCapableBeanFactory中:

  1. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
  2. //......
  3. //获取合适的构造方法,如果为空,则走默认的构造方法。
  4. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  5. if (ctors != null ||
  6. mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
  7. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  8. //如果发现有构造方法引用了依赖注入注解,比如:@AutoWired,则调用autowireConstructor方法进行注入
  9. return autowireConstructor(beanName, mbd, ctors, args);
  10. }
  11. // No special handling: simply use no-arg constructor.
  12. return instantiateBean(beanName, mbd);
  13. }

5。MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition

该接口用来合并BeanDefinition,也是对BeanDefinition处理一种扩展接口。
最常用的使用场景:AutowiredAnnotationBeanPostProcessor实现类中,通过该接口解析当前 bean 中所有
指定注解类型的熟悉:

  1. this.autowiredAnnotationTypes.add(Autowired.class);
  2. this.autowiredAnnotationTypes.add(Value.class);

默认解析上两种注解的属性,将其描述信息合并到当前对象的beanDefinition中,在后面属性填充populateBean的过程中,会取出这些对象,进行注入。
调用点在AbstractAutowireCapableBeanFactory中:

  1. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  2. throws BeanCreationException {
  3. // Instantiate the bean.
  4. BeanWrapper instanceWrapper = null;
  5. if (mbd.isSingleton()) {
  6. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  7. }
  8. //实例化 bean
  9. if (instanceWrapper == null) {
  10. instanceWrapper = createBeanInstance(beanName, mbd, args);
  11. }
  12. final Object bean = instanceWrapper.getWrappedInstance();
  13. Class<?> beanType = instanceWrapper.getWrappedClass();
  14. if (beanType != NullBean.class) {
  15. mbd.resolvedTargetType = beanType;
  16. }
  17. // Allow post-processors to modify the merged bean definition.
  18. synchronized (mbd.postProcessingLock) {
  19. if (!mbd.postProcessed) {
  20. try {
  21. //执行 postProcessMergedBeanDefinition 逻辑
  22. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  23. }
  24. catch (Throwable ex) {
  25. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  26. "Post-processing of merged bean definition failed", ex);
  27. }
  28. mbd.postProcessed = true;
  29. }
  30. }
  31. //......
  32. return exposedObject;
  33. }

6。InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation

实例化之后调用的方法,在AbstractAutowireCapableBeanFactory.populateBean()填充方法中会触发。
该方法默认返回为true,如果返回false,则中断populateBean方法,即不再执行属性注入的过程。
实际项目中,该扩展方法使用不多。

  1. protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  2. // ......
  3. boolean continueWithPropertyPopulation = true;
  4. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  5. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  6. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  7. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  8. if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  9. continueWithPropertyPopulation = false;
  10. break;
  11. }
  12. }
  13. }
  14. }
  15. if (!continueWithPropertyPopulation) {
  16. return;
  17. }
  18. //......
  19. }

7。SmartInstantiationAwareBeanPostProcessor.getEarlyBeanReference

getEarlyBeanReference方法只要有在 Spring 发生循环依赖时调用。首先,当bean 创建时,为了防止后续有循环依赖,会提前暴露回调方法,用于 bean 实例化的后置处理。getEarlyBeanReference方法就是在提前暴露的回调方法中触发。

具体调用点在DefaultSingletonBeanRegistry

  1. @Nullable
  2. protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  3. Object singletonObject = this.singletonObjects.get(beanName);
  4. //如果 bean 还未实例化,并且正在创建中。
  5. if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
  6. synchronized (this.singletonObjects) {
  7. //判断是否已经提前提前暴露了bean 引用。
  8. singletonObject = this.earlySingletonObjects.get(beanName);
  9. //如果运行循环依赖
  10. if (singletonObject == null && allowEarlyReference) {
  11. ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
  12. if (singletonFactory != null) {
  13. //则调用 getObject() 方法
  14. singletonObject = singletonFactory.getObject();
  15. this.earlySingletonObjects.put(beanName, singletonObject);
  16. this.singletonFactories.remove(beanName);
  17. }
  18. }
  19. }
  20. }
  21. return singletonObject;
  22. }

getObject()中调用getEarlyBeanReference方法完成 bean的初始化流程。

  1. protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
  2. Object exposedObject = bean;
  3. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  4. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  5. if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
  6. SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
  7. exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
  8. }
  9. }
  10. }
  11. return exposedObject;
  12. }

大致的流程:

当A实例化之后,Spring IOC会对A依赖的属性进行填充,此时如果发现A依赖了B,会去实例化B。同样在填充B的属性时,如果B也引用了A,就发生了循环依赖。因为A还未创建完成,还未注入Spring中。

Spring的做法是通过对创建中的缓存一个回调函数,类似于一个埋点操作,如果后续填充属性阶段,发生了循环依赖,则通过触发该回调函数来结束该bean的初始化。

​当对A实例化时,会提前暴露一个回调方法 ObjectFactory(Spring5中改为了函数式接口) 放入缓存。当B引用A,发现A还未实例化结束,就会通过缓存中的回调方法结束A的初始化流程,然后注入B。然后继续A的填充属性流程,将B注入A,然后结束循环依赖。

  1. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  2. isSingletonCurrentlyInCreation(beanName));
  3. //......
  4. if (earlySingletonExposure) {
  5. if (logger.isDebugEnabled()) {
  6. logger.debug("Eagerly caching bean '" + beanName +
  7. "' to allow for resolving potential circular references");
  8. }
  9. //添加回调方法,循环依赖时会回调
  10. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  11. }
  12. try {
  13. //填充属性,也就是发生循环依赖的地方
  14. populateBean(beanName, mbd, instanceWrapper);
  15. exposedObject = initializeBean(beanName, exposedObject, mbd);
  16. }
  17. catch (Throwable ex) {
  18. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  19. throw (BeanCreationException) ex;
  20. }
  21. else {
  22. throw new BeanCreationException(
  23. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  24. }
  25. }
  26. //......

8。InstantiationAwareBeanPostProcessor.postProcessPropertyValues

该方法用于属性注入,在 bean 初始化阶段属性填充时触发。@Autowired@Resource 等注解原理基于此方法实现。
具体调用点在AbstractAutowireCapableBeanFactorypopulateBean方法:

  1. protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  2. //......
  3. if (hasInstAwareBpps || needsDepCheck) {
  4. if (pvs == null) {
  5. pvs = mbd.getPropertyValues();
  6. }
  7. PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  8. if (hasInstAwareBpps) {
  9. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  10. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  11. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  12. //获取该方法的所有实现类
  13. pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
  14. if (pvs == null) {
  15. return;
  16. }
  17. }
  18. }
  19. }
  20. if (needsDepCheck) {
  21. checkDependencies(beanName, mbd, filteredPds, pvs);
  22. }
  23. }
  24. //......
  25. }

上述方法会获取所有postProcessPropertyValues的实现方法。例如:在AutowiredAnnotationBeanPostProcessor中实现方式如下,也就是依赖注入的实现代码:

  1. @Override
  2. public PropertyValues postProcessPropertyValues(
  3. PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
  4. InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
  5. try {
  6. metadata.inject(bean, beanName, pvs);
  7. }
  8. catch (BeanCreationException ex) {
  9. throw ex;
  10. }
  11. catch (Throwable ex) {
  12. throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
  13. }
  14. return pvs;
  15. }

9。ApplicationContextAwareProcessor.invokeAwareInterfaces

该扩展点用于执行各种驱动接口。在 bean实例化之后,属性填充之后,通过扩展接口,执行如下驱动接口:

  1. private void invokeAwareInterfaces(Object bean) {
  2. if (bean instanceof Aware) {
  3. if (bean instanceof EnvironmentAware) {
  4. ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
  5. }
  6. if (bean instanceof EmbeddedValueResolverAware) {
  7. ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
  8. }
  9. if (bean instanceof ResourceLoaderAware) {
  10. ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
  11. }
  12. if (bean instanceof ApplicationEventPublisherAware) {
  13. ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
  14. }
  15. if (bean instanceof MessageSourceAware) {
  16. ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
  17. }
  18. if (bean instanceof ApplicationContextAware) {
  19. ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
  20. }
  21. }
  22. }

所以,只需要实现以上6种驱动接口,就可以获得对应的容器相关的变量。


10。BeanFactoryPostProcessor.postProcessBeforeInitialization

BeanFactoryPostProcessor中的两个扩展接口是 Spring IOC过程中最后两个扩展接口。其中postProcessBeforeInitialization用于在 bean 实例化之后,afterPropertiesSet方法之前执行的前置接口。
用于对 bean 进行一些属性设置,上面的设置驱动的方法invokeAwareInterfaces便是实现了此接口。
调用点如下:

  1. protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
  2. if (System.getSecurityManager() != null) {
  3. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  4. invokeAwareMethods(beanName, bean);
  5. return null;
  6. }, getAccessControlContext());
  7. }
  8. else {
  9. invokeAwareMethods(beanName, bean);
  10. }
  11. Object wrappedBean = bean;
  12. if (mbd == null || !mbd.isSynthetic()) {
  13. //执行前置扩展方法
  14. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  15. }
  16. try {
  17. //执行 afterPropertiesSet 方法
  18. invokeInitMethods(beanName, wrappedBean, mbd);
  19. }
  20. catch (Throwable ex) {
  21. throw new BeanCreationException(
  22. (mbd != null ? mbd.getResourceDescription() : null),
  23. beanName, "Invocation of init method failed", ex);
  24. }
  25. if (mbd == null || !mbd.isSynthetic()) {
  26. //执行后置扩展方法
  27. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  28. }
  29. return wrappedBean;
  30. }

11。InitializingBean.afterPropertiesSet

用于bean实例化之后,设置熟悉的方法。
上面已经提到,在invokeInitMethods方法中会触发该方法调用:

  1. protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
  2. throws Throwable {
  3. boolean isInitializingBean = (bean instanceof InitializingBean);
  4. if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
  5. if (logger.isDebugEnabled()) {
  6. logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
  7. }
  8. if (System.getSecurityManager() != null) {
  9. try {
  10. //执行afterPropertiesSet
  11. AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
  12. ((InitializingBean) bean).afterPropertiesSet();
  13. return null;
  14. }, getAccessControlContext());
  15. }
  16. catch (PrivilegedActionException pae) {
  17. throw pae.getException();
  18. }
  19. }
  20. else {
  21. //执行afterPropertiesSet
  22. ((InitializingBean) bean).afterPropertiesSet();
  23. }
  24. }
  25. }

12。BeanFactoryPostProcessor.postProcessAfterInitialization

该方法Spring IOC过程中最后一个常用的扩展点,用于 bean 初始化之后的后置处理。
Spring AOP 原理便是基于此扩展点实现,实现方式在AbstractAutoProxyCreator中:

  1. public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
  2. if (bean != null) {
  3. Object cacheKey = getCacheKey(bean.getClass(), beanName);
  4. if (!this.earlyProxyReferences.contains(cacheKey)) {
  5. return wrapIfNecessary(bean, beanName, cacheKey);
  6. }
  7. }
  8. return bean;
  9. }

总结

我们使用 Spring 或者 SpringBoot 时,通过 Spring 预留的以上扩展接口,可以方便的实现对 Spring IOC 过程中的逻辑做一些扩展和增强。通 Servlet 规范一样,可以理解为面向接口编程。