Spring扩展点总结

spring中bean的扩展点

经历了一系列复杂的spring应用后,你的项目可能已经用上注解,也用上了xxx.properties,你对这神奇的用法感到欣喜,但你不知道他是怎么被实现的,现在就让我们来揭开这些神秘的面纱。

BeanDefinition与BeanFactory扩展

Spring生成bean的过程这篇文章中,我们了解了spring在生成bean前会先生成bean的定义,然后注册到BeanFactory中,再之后才能生成bean。那么对于从xml配置好的BeanDefinition,如果想要增加删除修改该怎么办呢?

BeanDefinitionRegistryPostProcessor接口

BeanDefinitionRegistryPostProcessor接口继承了BeanFactoryPostProcessor接口,BeanFactoryPostProcessor接口随后我们也会讲到这个接口。

接口描述


  
  1. /**
  2. * Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for
  3. * the registration of further bean definitions <i>before</i> regular
  4. * BeanFactoryPostProcessor detection kicks in. In particular,
  5. * BeanDefinitionRegistryPostProcessor may register further bean definitions
  6. * which in turn define BeanFactoryPostProcessor instances.
  7. *
  8. * @author Juergen Hoeller
  9. * @since 3.0.1
  10. * @see org.springframework.context.annotation.ConfigurationClassPostProcessor
  11. */
  12. public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
  13. /**
  14. * Modify the application context's internal bean definition registry after its
  15. * standard initialization. All regular bean definitions will have been loaded,
  16. * but no beans will have been instantiated yet. This allows for adding further
  17. * bean definitions before the next post-processing phase kicks in.
  18. * @param registry the bean definition registry used by the application context
  19. * @throws org.springframework.beans.BeansException in case of errors
  20. */
  21. void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
  22. }

 

这个接口扩展了标准的BeanFactoryPostProcessor 接口,允许在普通的BeanFactoryPostProcessor接口实现类执行之前注册更多的BeanDefinition。特别地是,BeanDefinitionRegistryPostProcessor可以注册BeanFactoryPostProcessor的BeanDefinition。

postProcessBeanDefinitionRegistry方法可以修改在BeanDefinitionRegistry接口实现类中注册的任意BeanDefinition,也可以增加和删除BeanDefinition。原因是这个方法执行前所有常规的BeanDefinition已经被加载到BeanDefinitionRegistry接口实现类中,但还没有bean被实例化。

接口应用


  
  1. import org.slf4j.Logger;
  2. import org.slf4j.LoggerFactory;
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  5. import org.springframework.beans.factory.support.BeanDefinitionRegistry;
  6. import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
  7. public class DefaultBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
  8. private Logger logger = LoggerFactory.getLogger(this.getClass());
  9. @Override
  10. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  11. logger.info("BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法,在这里可以增加修改删除bean的定义");
  12. }
  13. @Override
  14. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  15. logger.info("BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法,在这里可以对beanFactory做一些操作");
  16. }
  17. }

我们仅仅需要写一个类实现接口,然后将这个类配置到spring的xml配置中。以下是我写的一个简单的实现类:

实际上,Mybatis中org.mybatis.spring.mapper.MapperScannerConfigurer就实现了该方法,在只有接口没有实现类的情况下找到接口方法与sql之间的联系从而生成BeanDefinition并注册。而Spring的org.springframework.context.annotation.ConfigurationClassPostProcessor也是用来将注解@Configuration中的相关生成bean的方法所对应的BeanDefinition进行注册。

BeanFactoryPostProcessor接口

BeanFactory生成后,如果想对BeanFactory进行一些处理,该怎么办呢?BeanFactoryPostProcessor接口就是用来处理BeanFactory的。

接口描述


  
  1. /**
  2. * Allows for custom modification of an application context's bean definitions,
  3. * adapting the bean property values of the context's underlying bean factory.
  4. *
  5. * <p>Application contexts can auto-detect BeanFactoryPostProcessor beans in
  6. * their bean definitions and apply them before any other beans get created.
  7. *
  8. * <p>Useful for custom config files targeted at system administrators that
  9. * override bean properties configured in the application context.
  10. *
  11. * <p>See PropertyResourceConfigurer and its concrete implementations
  12. * for out-of-the-box solutions that address such configuration needs.
  13. *
  14. * <p>A BeanFactoryPostProcessor may interact with and modify bean
  15. * definitions, but never bean instances. Doing so may cause premature bean
  16. * instantiation, violating the container and causing unintended side-effects.
  17. * If bean instance interaction is required, consider implementing
  18. * {@link BeanPostProcessor} instead.
  19. *
  20. * @author Juergen Hoeller
  21. * @since 06.07.2003
  22. * @see BeanPostProcessor
  23. * @see PropertyResourceConfigurer
  24. */
  25. public interface BeanFactoryPostProcessor {
  26. /**
  27. * Modify the application context's internal bean factory after its standard
  28. * initialization. All bean definitions will have been loaded, but no beans
  29. * will have been instantiated yet. This allows for overriding or adding
  30. * properties even to eager-initializing beans.
  31. * @param beanFactory the bean factory used by the application context
  32. * @throws org.springframework.beans.BeansException in case of errors
  33. */
  34. void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
  35. }

这个接口允许自定义修改应用程序上下文的BeanDefinition,调整上下文的BeanFactory的bean属性值。应用程序上下文可以在BeanFactory的BeanDefinition中自动检测BeanFactoryPostProcessor bean,并在创建任何其他bean之前应用它们。对于定位于系统管理员的自定义配置文件非常有用,它们将覆盖应用程序上下文中配置的bean属性。请参阅PropertyResourceConfigurer及其具体实现,了解解决此类配置需求的开箱即用解决方案。BeanFactoryPostProcessor可能与bean定义交互并修改,但永远不应该将bean实例化。 这样做可能会导致过早的bean实例化,违反容器执行顺序并导致意想不到的副作用。如果需要bean实例交互,请考虑实现BeanPostProcessor接口。

postProcessBeanFactory方法在BeanFactory初始化后,所有的bean定义都被加载,但是没有bean会被实例化时,允许重写或添加属性。

接口应用

与DefaultBeanDefinitionRegistryPostProcessor接口一样,实现并配置到spring的xml配置中即可。

最常用的一个应用就是org.springframework.beans.factory.config.PropertyPlaceholderConfigurer,BeanDefinition生成后,可能某些参数是${key},这个实现类就是把前边这种参数转换成xxx.properties中key所对应的值。

Bean实例化中的扩展

前一小节关注的是BeanDefinition和BeanFactory,那么在bean的实例化过程中会调用一些特定的接口实现类,这些接口都有哪些?

InstantiationAwareBeanPostProcessor接口

接口描述


  
  1. /**
  2. * Subinterface of {@link BeanPostProcessor} that adds a before-instantiation callback,
  3. * and a callback after instantiation but before explicit properties are set or
  4. * autowiring occurs.
  5. *
  6. * <p>Typically used to suppress default instantiation for specific target beans,
  7. * for example to create proxies with special TargetSources (pooling targets,
  8. * lazily initializing targets, etc), or to implement additional injection strategies
  9. * such as field injection.
  10. *
  11. * <p><b>NOTE:</b> This interface is a special purpose interface, mainly for
  12. * internal use within the framework. It is recommended to implement the plain
  13. * {@link BeanPostProcessor} interface as far as possible, or to derive from
  14. * {@link InstantiationAwareBeanPostProcessorAdapter} in order to be shielded
  15. * from extensions to this interface.
  16. *
  17. * @author Juergen Hoeller
  18. * @author Rod Johnson
  19. * @since 1.2
  20. * @see org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#setCustomTargetSourceCreators
  21. * @see org.springframework.aop.framework.autoproxy.target.LazyInitTargetSourceCreator
  22. */
  23. public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
  24. /**
  25. * Apply this BeanPostProcessor <i>before the target bean gets instantiated</i>.
  26. * The returned bean object may be a proxy to use instead of the target bean,
  27. * effectively suppressing default instantiation of the target bean.
  28. * <p>If a non-null object is returned by this method, the bean creation process
  29. * will be short-circuited. The only further processing applied is the
  30. * {@link #postProcessAfterInitialization} callback from the configured
  31. * {@link BeanPostProcessor BeanPostProcessors}.
  32. * <p>This callback will only be applied to bean definitions with a bean class.
  33. * In particular, it will not be applied to beans with a "factory-method".
  34. * <p>Post-processors may implement the extended
  35. * {@link SmartInstantiationAwareBeanPostProcessor} interface in order
  36. * to predict the type of the bean object that they are going to return here.
  37. * @param beanClass the class of the bean to be instantiated
  38. * @param beanName the name of the bean
  39. * @return the bean object to expose instead of a default instance of the target bean,
  40. * or {@code null} to proceed with default instantiation
  41. * @throws org.springframework.beans.BeansException in case of errors
  42. * @see org.springframework.beans.factory.support.AbstractBeanDefinition#hasBeanClass
  43. * @see org.springframework.beans.factory.support.AbstractBeanDefinition#getFactoryMethodName
  44. */
  45. Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;
  46. /**
  47. * Perform operations after the bean has been instantiated, via a constructor or factory method,
  48. * but before Spring property population (from explicit properties or autowiring) occurs.
  49. * <p>This is the ideal callback for performing field injection on the given bean instance.
  50. * See Spring's own {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor}
  51. * for a typical example.
  52. * @param bean the bean instance created, with properties not having been set yet
  53. * @param beanName the name of the bean
  54. * @return {@code true} if properties should be set on the bean; {@code false}
  55. * if property population should be skipped. Normal implementations should return {@code true}.
  56. * Returning {@code false} will also prevent any subsequent InstantiationAwareBeanPostProcessor
  57. * instances being invoked on this bean instance.
  58. * @throws org.springframework.beans.BeansException in case of errors
  59. */
  60. boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
  61. /**
  62. * Post-process the given property values before the factory applies them
  63. * to the given bean. Allows for checking whether all dependencies have been
  64. * satisfied, for example based on a "Required" annotation on bean property setters.
  65. * <p>Also allows for replacing the property values to apply, typically through
  66. * creating a new MutablePropertyValues instance based on the original PropertyValues,
  67. * adding or removing specific values.
  68. * @param pvs the property values that the factory is about to apply (never {@code null})
  69. * @param pds the relevant property descriptors for the target bean (with ignored
  70. * dependency types - which the factory handles specifically - already filtered out)
  71. * @param bean the bean instance created, but whose properties have not yet been set
  72. * @param beanName the name of the bean
  73. * @return the actual property values to apply to the given bean
  74. * (can be the passed-in PropertyValues instance), or {@code null}
  75. * to skip property population
  76. * @throws org.springframework.beans.BeansException in case of errors
  77. * @see org.springframework.beans.MutablePropertyValues
  78. */
  79. PropertyValues postProcessPropertyValues(
  80. PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
  81. throws BeansException;
  82. }

这个接口是BeanPostProcessor的子接口,用于在实例化之后,但在设置显式属性或自动装配之前,设置实例化之前的回调函数。通常用于抑制特定目标bean的默认实例化,例如,创建具有特殊TargetSources(池化目标,延迟初始化目标等)的代理,或者实现其他注入策略,例如字段注入。注意:这个接口是一个专用接口,主要用于框架内的内部使用。 建议尽可能实现简单的BeanPostProcessor接口,或者从InstantiationAwareBeanPostProcessorAdapter派生,以便屏蔽此接口的扩展。

postProcessBeforeInstantiation方法,在目标bean实例化之前创建bean,如果在这里创建了bean,则不会走默认的实例化过程,通常用来创建代理。注意工厂方法生成的bean不会走这个方法。

postProcessAfterInstantiation方法,在目标bean实例化后,但是没有进行属性填充前执行的方法。

postProcessPropertyValues方法,在将给定属性值设置到到给定的bean后,对其进行后处理。 允许检查所有的依赖关系是否被满足,例如基于bean属性设置器上的“Required”注解。还允许替换要应用的属性值,通常通过创建基于原始PropertyValues的新MutablePropertyValues实例,添加或删除特定值。

接口应用

这个接口spring不建议用户直接实现,如果必须在这些扩展点应用自己的回调函数,spring建议继承InstantiationAwareBeanPostProcessorAdapter,重写相应的方法即可。

org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator,基于beanName创建代理,就是应用了这个接口,在生成bean前生成代理bean,从而替代默认的实例化。

BeanPostProcessor接口

接口描述


  
  1. /**
  2. * Factory hook that allows for custom modification of new bean instances,
  3. * e.g. checking for marker interfaces or wrapping them with proxies.
  4. *
  5. * <p>ApplicationContexts can autodetect BeanPostProcessor beans in their
  6. * bean definitions and apply them to any beans subsequently created.
  7. * Plain bean factories allow for programmatic registration of post-processors,
  8. * applying to all beans created through this factory.
  9. *
  10. * <p>Typically, post-processors that populate beans via marker interfaces
  11. * or the like will implement {@link #postProcessBeforeInitialization},
  12. * while post-processors that wrap beans with proxies will normally
  13. * implement {@link #postProcessAfterInitialization}.
  14. *
  15. * @author Juergen Hoeller
  16. * @since 10.10.2003
  17. * @see InstantiationAwareBeanPostProcessor
  18. * @see DestructionAwareBeanPostProcessor
  19. * @see ConfigurableBeanFactory#addBeanPostProcessor
  20. * @see BeanFactoryPostProcessor
  21. */
  22. public interface BeanPostProcessor {
  23. /**
  24. * Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
  25. * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
  26. * or a custom init-method). The bean will already be populated with property values.
  27. * The returned bean instance may be a wrapper around the original.
  28. * @param bean the new bean instance
  29. * @param beanName the name of the bean
  30. * @return the bean instance to use, either the original or a wrapped one;
  31. * if {@code null}, no subsequent BeanPostProcessors will be invoked
  32. * @throws org.springframework.beans.BeansException in case of errors
  33. * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
  34. */
  35. Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
  36. /**
  37. * Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
  38. * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
  39. * or a custom init-method). The bean will already be populated with property values.
  40. * The returned bean instance may be a wrapper around the original.
  41. * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
  42. * instance and the objects created by the FactoryBean (as of Spring 2.0). The
  43. * post-processor can decide whether to apply to either the FactoryBean or created
  44. * objects or both through corresponding {@code bean instanceof FactoryBean} checks.
  45. * <p>This callback will also be invoked after a short-circuiting triggered by a
  46. * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
  47. * in contrast to all other BeanPostProcessor callbacks.
  48. * @param bean the new bean instance
  49. * @param beanName the name of the bean
  50. * @return the bean instance to use, either the original or a wrapped one;
  51. * if {@code null}, no subsequent BeanPostProcessors will be invoked
  52. * @throws org.springframework.beans.BeansException in case of errors
  53. * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
  54. * @see org.springframework.beans.factory.FactoryBean
  55. */
  56. Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
  57. }

这个接口,允许自定义修改新的bean实例,例如检查标记接口或用代理包装,注意,如果有相互依赖的bean,这里可能无法使用代理。

postProcessBeforeInitialization方法,在任何bean初始化回调(如InitializingBean的afterPropertiesSet或自定义init方法)之前,将此BeanPostProcessor应用于给定的新的bean实例。 这个bean已经被填充了属性值。 返回的bean实例可能是原始的包装器。

postProcessAfterInitialization方法,在Bean初始化回调(如InitializingBean的afterPropertiesSet或自定义init方法)之后,将此BeanPostProcessor应用于给定的新bean实例。 这个bean已经被填充了属性值。 返回的bean实例可能是原始的包装器。这个方法也会在InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法生成对象后再次不让他生成对象(具体可以参考Spring生成bean的过程)。

接口应用

org.springframework.context.support.ApplicationContextAwareProcessor就是在bean初始化回调之前,注入应用上下文的。

其他扩展点

InitializingBean接口

在执行完BeanPostProcessor的postProcessBeforeInitialization方法后,如果这个bean实现了InitializingBean接口,则会去调用afterPropertiesSet方法。

各种Aware

在在执行完BeanPostProcessor的postProcessBeforeInitialization方法前,如果bean实现了BeanNameAware或BeanClassLoaderAware或BeanFactoryAware,则会调用接口相关的方法,入参就是这个bean关心的值。

ApplicationContextAwareProcessor,作用是在一个bean初始化之前,如果这个bean有Aware接口,实现了EnvironmentAware,EmbeddedValueResolverAware,ResourceLoaderAware,ApplicationEventPublisherAware,MessageSourceAware,ApplicationContextAware相关接口,就通过这些aware的相关接口将上下文设置进去,上述接口除了EmbeddedValueResolverAware接口ClassPathXmlApplicationContext没有实现,其他都实现了,也就是说,调用这些接口的方法入参都是ClassPathXmlApplicationContext就可以了。EmbeddedValueResolverAware的入参是EmbeddedValueResolver,它的构造函数入参是上下文中的beanFactory。

BeanDefinition入口扩展

在定义bean时,可以指定构造函数,设置属性,还可以设置init-method和destroy-method。构造函数不用说,设置属性是在InstantiationAwareBeanPostProcessor#PostProcessPropertyValues方法后执行的,init-method是在InitializingBean的afterPropertiesSet方法后执行的,而destroy-method是在容器关闭是被调用的。

扩展点在spring中的注入

前三小节我们了解了很多扩展点,那这些扩展点中的接口是怎么在spring中生效的呢,换句话说在什么时候被调用或被添加到BeanFactory中等待调用呢?

容器级别

我们得从上下文的抽象类AbstractApplicationContext#refresh方法讲起。


  
  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized (this.startupShutdownMonitor) {
  4. // Prepare this context for refreshing.
  5. // 设置上下文启动时间和活跃标记,同时加载属性资源。
  6. prepareRefresh();
  7. // Tell the subclass to refresh the internal bean factory.
  8. // 停掉之前启动的beanFactory如果有的话,同时新生成一个beanFactory,加载配置中的BeanDefinition。
  9. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  10. // Prepare the bean factory for use in this context.
  11. // 给beanFactory设置类加载器,添加后置处理器`ApplicationContextAwareProcessor`等等。
  12. prepareBeanFactory(beanFactory);
  13. try {
  14. // Allows post-processing of the bean factory in context subclasses.
  15. postProcessBeanFactory(beanFactory);
  16. // Invoke factory processors registered as beans in the context.
  17. invokeBeanFactoryPostProcessors(beanFactory);
  18. // Register bean processors that intercept bean creation.
  19. registerBeanPostProcessors(beanFactory);
  20. // Initialize message source for this context.
  21. initMessageSource();
  22. // Initialize event multicaster for this context.
  23. initApplicationEventMulticaster();
  24. // Initialize other special beans in specific context subclasses.
  25. onRefresh();
  26. // Check for listener beans and register them.
  27. registerListeners();
  28. // Instantiate all remaining (non-lazy-init) singletons.
  29. finishBeanFactoryInitialization(beanFactory);
  30. // Last step: publish corresponding event.
  31. finishRefresh();
  32. }
  33. catch (BeansException ex) {
  34. if (logger.isWarnEnabled()) {
  35. logger.warn("Exception encountered during context initialization - " +
  36. "cancelling refresh attempt: " + ex);
  37. }
  38. // Destroy already created singletons to avoid dangling resources.
  39. destroyBeans();
  40. // Reset 'active' flag.
  41. cancelRefresh(ex);
  42. // Propagate exception to caller.
  43. throw ex;
  44. }
  45. finally {
  46. // Reset common introspection caches in Spring's core, since we
  47. // might not ever need metadata for singleton beans anymore...
  48. resetCommonCaches();
  49. }
  50. }
  51. }

invokeBeanFactoryPostProcessors(beanFactory)方法就是第一小节提到的BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor的调用。

invokeBeanFactoryPostProcessors方法的调用逻辑:

如果beanFactory是BeanDefinitionRegistry的实现类

拿到入参所有的BeanFactoryPostProcessor接口实现类,挑选出实现BeanDefinitionRegistryPostProcessor接口的实现类先执行postProcessBeanDefinitionRegistry方法。

接下来调用beanFactory中实现BeanDefinitionRegistryPostProcessor接口的实现类中实现PriorityOrdered接口的实现类,调用这些实现类前先根据PriorityOrdered的getOrder方法进行排序,然后再按顺序调用postProcessBeanDefinitionRegistry方法。

接下来再调用beanFactory中实现BeanDefinitionRegistryPostProcessor接口的实现类中实现了Ordered接口的类,也是按顺序调用postProcessBeanDefinitionRegistry方法。

最后调用beanFactory中其他的实现BeanDefinitionRegistryPostProcessor接口的实现类的postProcessBeanDefinitionRegistry方法。

最后的最后,先调用入参中所有实现BeanDefinitionRegistryPostProcessor接口的实现类的postProcessBeanFactory方法,再调用入参中实现了BeanFactoryPostProcessor接口的实现类的postProcessBeanFactory方法。

如果不是则只把入参中的BeanFactoryPostProcessor实现类全部调用一遍。

上边都做完了,接着从beanFactory中获取实现了BeanFactoryPostProcessor接口的bean(没有被执行过),也是分为三类,PriorityOrdered组优先调用,Ordered其次,其他垫底。
最终清除beanFactory的metaData缓存(主要是清除类与beanname的映射缓存)

registerBeanPostProcessors(beanFactory)方法就是第二小节中BeanPostProcessor接口实现类的注册。

registerBeanPostProcessors方法的调用逻辑:

先添加BeanPostProcessorChecker。

然后把beanFactory中实现BeanPostProcessor接口的实现类分成四个部分分别添加到beanFactory。

PriorityOrdered部分,实现了PriorityOrdered接口且并不属于MergedBeanDefinitionPostProcessor的

Ordered部分,实现了Ordered接口且并不属于MergedBeanDefinitionPostProcessor的

其他的不属于MergedBeanDefinitionPostProcessor的

属于MergedBeanDefinitionPostProcessor的

其中PriorityOrdered和Ordered部分先排序,然后按上边的顺序分别加入到beanFactory的beanPostProcessors属性中

bean级别

其余的bean上的接口属性之类的,都是在bean的生成中逐个调用的。

小节

下面由一张图来总结一下扩展点之间的调用顺序。

upload successful

 

文章来源: blog.csdn.net,作者:轻狂书生FS,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/LookForDream_/article/details/105086781

(完)