spring 源码分析之BeanPostProcessor
1.官方解答:
Factory hook that allows for custom modification of new bean instances, e.g. checking for marker interfaces or wrapping them with proxies.
ApplicationContexts can autodetect BeanPostProcessor beans in their bean definitions and apply them to any beans subsequently created. Plain bean factories allow for programmatic registration of post-processors, applying to all beans created through this factory.
Typically, post-processors that populate beans via marker interfaces or the like will implement postProcessBeforeInitialization(java.lang.Object, java.lang.String), while post-processors that wrap beans with proxies will normally implement postProcessAfterInitialization(java.lang.Object, java.lang.String).
ApplicationContext自动查找BeanPostProcessor bean并应用到接下来创建的任何bean。
普通的bean factory可以使用编程的方式注册post-processor,应用到这个bean factory产生的所有bean。例:
2.子类实现
AbstractAdvisingBeanPostProcessor:Base class for BeanPostProcessor implementations that apply a Spring AOP Advisor to specific beans.
AbstractAdvisorAutoProxyCreator:Generic auto proxy creator that builds AOP proxies for specific beans based on detected Advisors for each bean.
AbstractAutoProxyCreator:BeanPostProcessor implementation that wraps each eligible bean with an AOP proxy, delegating to specified interceptors before invoking the bean itself.
AdvisorAdapterRegistrationManager:BeanPostProcessor that registers AdvisorAdapter beans in the BeanFactory with an AdvisorAdapterRegistry (by default the GlobalAdvisorAdapterRegistry).The only requirement for it to work is that it needs to be defined in application context along with "non-native" Spring AdvisorAdapters that need to be "recognized" by Spring's AOP framework.
AnnotationAwareAspectJAutoProxyCreator:
AspectJAwareAdvisorAutoProxyCreator subclass that processes all AspectJ annotation aspects in the current application context, as well as Spring Advisors.Any AspectJ annotated classes will automatically be recognized, and their advice applied if Spring AOP's proxy-based model is capable of applying it. This covers method execution joinpoints.If the <aop:include> element is used, only @AspectJ beans with names matched by an include pattern will be considered as defining aspects to use for Spring auto-proxying.Processing of Spring Advisors follows the rules established in AbstractAdvisorAutoProxyCreator.
AspectJAwareAdvisorAutoProxyCreator:AbstractAdvisorAutoProxyCreator subclass that exposes AspectJ's invocation context and understands AspectJ's rules for advice precedence when multiple pieces of advice come from the same aspect.
AsyncAnnotationBeanPostProcessor:
Bean post-processor that automatically applies asynchronous invocation behavior to any bean that carries the Async annotation at class or method-level by adding a corresponding AsyncAnnotationAdvisor to the exposed proxy (either an existing AOP proxy or a newly generated proxy that implements all of the target's interfaces).
The TaskExecutor responsible for the asynchronous execution may be provided as well as the annotation type that indicates a method should be invoked asynchronously. If no annotation type is specified, this post- processor will detect both Spring's @Async annotation as well as the EJB 3.1 javax.ejb.Asynchronous annotation. For methods having a void return type, any exception thrown during the asynchronous method invocation cannot be accessed by the caller. An AsyncUncaughtExceptionHandler can be specified to handle these cases. Note: The underlying async advisor applies before existing advisors by default, in order to switch to async execution as early as possible in the invocation chain.
AutowiredAnnotationBeanPostProcessor:
BeanPostProcessor implementation that autowires annotated fields, setter methods and arbitrary config methods. Such members to be injected are detected through a Java 5 annotation: by default, Spring's @Autowired and @Value annotations.
Also supports JSR-330's @Inject annotation, if available, as a direct alternative to Spring's own @Autowired
BeanNameAutoProxyCreator,
Auto proxy creator that identifies beans to proxy via a list of names. Checks for direct, "xxx*", and "*xxx" matches.
For configuration details, see the javadoc of the parent class AbstractAutoProxyCreator. Typically, you will specify a list of interceptor names to apply to all identified beans, via the "interceptorNames" property.
BeanValidationPostProcessor,
Simple BeanPostProcessor that checks JSR-303 constraint annotations in Spring-managed beans, throwing an initialization exception in case of constraint violations right before calling the bean's init method (if any).
CommonAnnotationBeanPostProcessor,
BeanPostProcessor implementation that supports common Java annotations out of the box, in particular the JSR-250 annotations in the javax.annotation package. These common Java annotations are supported in many Java EE 5 technologies (e.g. JSF 1.2), as well as in Java 6's JAX-WS.
NOTE: A default CommonAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom CommonAnnotationBeanPostProcessor bean definition! NOTE: Annotation injection will be performed before XML injection; thus the latter configuration will override the former for properties wired through both approaches.
DefaultAdvisorAutoProxyCreator,
BeanPostProcessor implementation that creates AOP proxies based on all candidate Advisors in the current BeanFactory. This class is completely generic; it contains no special code to handle any particular aspects, such as pooling aspects.
It's possible to filter out advisors - for example, to use multiple post processors of this type in the same factory - by setting the usePrefix property to true, in which case only advisors beginning with the DefaultAdvisorAutoProxyCreator's bean name followed by a dot (like "aapc.") will be used. This default prefix can be changed from the bean name by setting the advisorBeanNamePrefix property. The separator (.) will also be used in this case.
InfrastructureAdvisorAutoProxyCreator,
Auto-proxy creator that considers infrastructure Advisor beans only, ignoring any application-defined Advisors.
InitDestroyAnnotationBeanPostProcessor,
BeanPostProcessor implementation that invokes annotated init and destroy methods. Allows for an annotation alternative to Spring's InitializingBean and DisposableBean callback interfaces.
The actual annotation types that this post-processor checks for can be configured through the "initAnnotationType" and "destroyAnnotationType" properties. Any custom annotation can be used, since there are no required annotation attributes. Init and destroy annotations may be applied to methods of any visibility: public, package-protected, protected, or private. Multiple such methods may be annotated, but it is recommended to only annotate one single init method and destroy method, respectively. Spring's CommonAnnotationBeanPostProcessor supports the JSR-250 PostConstruct and PreDestroy annotations out of the box, as init annotation and destroy annotation, respectively. Furthermore, it also supports the Resource annotation for annotation-driven injection of named beans.
InstantiationAwareBeanPostProcessorAdapter,
Adapter that implements all methods on SmartInstantiationAwareBeanPostProcessor as no-ops, which will not change normal processing of each bean instantiated by the container. Subclasses may override merely those methods that they are actually interested in.
Note that this base class is only recommendable if you actually require InstantiationAwareBeanPostProcessor functionality. If all you need is plain BeanPostProcessor functionality, prefer a straight implementation of that (simpler) interface.
JmsListenerAnnotationBeanPostProcessor,
Bean post-processor that registers methods annotated with JmsListener to be invoked by a JMS message listener container created under the cover by a JmsListenerContainerFactory according to the parameters of the annotation.
Annotated methods can use flexible arguments as defined by JmsListener. This post-processor is automatically registered by Spring's <jms:annotation-driven> XML element, and also by the EnableJms annotation. Auto-detect any JmsListenerConfigurer instances in the container, allowing for customization of the registry to be used, the default container factory or for fine-grained control over endpoints registration. See EnableJms Javadoc for complete usage details.
LoadTimeWeaverAwareProcessor,
BeanPostProcessor implementation that passes the context's default LoadTimeWeaver to beans that implement the LoadTimeWeaverAware interface.
Application contexts will automatically register this with their underlying bean factory, provided that a default LoadTimeWeaver is actually available. Applications should not use this class directly.
MethodValidationPostProcessor,
A convenient BeanPostProcessor implementation that delegates to a JSR-303 provider for performing method-level validation on annotated methods.
Applicable methods have JSR-303 constraint annotations on their parameters and/or on their return value (in the latter case specified at the method level, typically as inline annotation), e.g.: public @NotNull Object myValidMethod(@NotNull String arg1, @Max(10) int arg2) Target classes with such annotated methods need to be annotated with Spring's Validated annotation at the type level, for their methods to be searched for inline constraint annotations. Validation groups can be specified through @Validated as well. By default, JSR-303 will validate against its default group only. As of Spring 4.0, this functionality requires either a Bean Validation 1.1 provider (such as Hibernate Validator 5.x) or the Bean Validation 1.0 API with Hibernate Validator 4.3. The actual provider will be autodetected and automatically adapted.
PersistenceAnnotationBeanPostProcessor,
BeanPostProcessor that processes PersistenceUnit and PersistenceContext annotations, for injection of the corresponding JPA resources EntityManagerFactory and EntityManager. Any such annotated fields or methods in any Spring-managed object will automatically be injected.
This post-processor will inject sub-interfaces of EntityManagerFactory and EntityManager if the annotated fields or methods are declared as such. The actual type will be verified early, with the exception of a shared ("transactional") EntityManager reference, where type mismatches might be detected as late as on the first actual invocation. Note: In the present implementation, PersistenceAnnotationBeanPostProcessor only supports @PersistenceUnit and @PersistenceContext with the "unitName" attribute, or no attribute at all (for the default unit). If those annotations are present with the "name" attribute at the class level, they will simply be ignored, since those only serve as deployment hint (as per the Java EE 5 specification).
PersistenceExceptionTranslationPostProcessor,
Bean post-processor that automatically applies persistence exception translation to any bean marked with Spring's @Repository annotation, adding a corresponding PersistenceExceptionTranslationAdvisor to the exposed proxy (either an existing AOP proxy or a newly generated proxy that implements all of the target's interfaces).
Translates native resource exceptions to Spring's DataAccessException hierarchy. Autodetects beans that implement the PersistenceExceptionTranslator interface, which are subsequently asked to translate candidate exceptions. All of Spring's applicable resource factories (e.g. LocalContainerEntityManagerFactoryBean) implement the PersistenceExceptionTranslator interface out of the box. As a consequence, all that is usually needed to enable automatic exception translation is marking all affected beans (such as Repositories or DAOs) with the @Repository annotation, along with defining this post-processor as a bean in the application context.
PortletContextAwareProcessor,
BeanPostProcessor implementation that passes the PortletContext to beans that implement the PortletContextAware interface.
Portlet application contexts will automatically register this with their underlying bean factory. Applications do not use this directly.
RequiredAnnotationBeanPostProcessor,
BeanPostProcessor implementation that enforces required JavaBean properties to have been configured. Required bean properties are detected through a Java 5 annotation: by default, Spring's Required annotation.
The motivation for the existence of this BeanPostProcessor is to allow developers to annotate the setter properties of their own classes with an arbitrary JDK 1.5 annotation to indicate that the container must check for the configuration of a dependency injected value. This neatly pushes responsibility for such checking onto the container (where it arguably belongs), and obviates the need (in part) for a developer to code a method that simply checks that all required properties have actually been set. Please note that an 'init' method may still need to implemented (and may still be desirable), because all that this class does is enforce that a 'required' property has actually been configured with a value. It does not check anything else... In particular, it does not check that a configured value is not null. Note: A default RequiredAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom RequiredAnnotationBeanPostProcessor bean definition.
ScheduledAnnotationBeanPostProcessor,
Bean post-processor that registers methods annotated with @Scheduled to be invoked by a TaskScheduler according to the "fixedRate", "fixedDelay", or "cron" expression provided via the annotation.
This post-processor is automatically registered by Spring's <task:annotation-driven> XML element, and also by the @EnableScheduling annotation. Auto-detects any SchedulingConfigurer instances in the container, allowing for customization of the scheduler to be used or for fine-grained control over task registration (e.g. registration of Trigger tasks. See the @EnableScheduling javadocs for complete usage details.
ScriptFactoryPostProcessor,
BeanPostProcessor that handles ScriptFactory definitions, replacing each factory with the actual scripted Java object generated by it.
This is similar to the FactoryBean mechanism, but is specifically tailored for scripts and not built into Spring's core container itself but rather implemented as an extension.
ServerEndpointExporter,
Detects beans of type ServerEndpointConfig and registers with the standard Java WebSocket runtime. Also detects beans annotated with ServerEndpoint and registers them as well. Although not required, it is likely annotated endpoints should have their configurator property set to SpringConfigurator.
When this class is used, by declaring it in Spring configuration, it should be possible to turn off a Servlet container's scan for WebSocket endpoints. This can be done with the help of the <absolute-ordering> element in web.xml.
ServletContextAwareProcessor,
BeanPostProcessor implementation that passes the ServletContext to beans that implement the ServletContextAware interface.
Web application contexts will automatically register this with their underlying bean factory. Applications do not use this directly.
SimplePortletPostProcessor,
Bean post-processor that applies initialization and destruction callbacks to beans that implement the Portlet interface.
After initialization of the bean instance, the Portlet init method will be called with a PortletConfig that contains the bean name of the Portlet and the PortletContext that it is running in. Before destruction of the bean instance, the Portlet destroy will be called. Note that this post-processor does not support Portlet initialization parameters. Bean instances that implement the Portlet interface are supposed to be configured like any other Spring bean, that is, through constructor arguments or bean properties. For reuse of a Portlet implementation in a plain Portlet container and as a bean in a Spring context, consider deriving from Spring's GenericPortletBean base class that applies Portlet initialization parameters as bean properties, supporting both initialization styles. Alternatively, consider wrapping a Portlet with Spring's PortletWrappingController. This is particularly appropriate for existing Portlet classes, allowing to specify Portlet initialization parameters etc.
SimpleServletPostProcessor
BeanPostProcessor that applies initialization and destruction callbacks to beans that implement the Servlet interface.
After initialization of the bean instance, the Servlet init method will be called with a ServletConfig that contains the bean name of the Servlet and the ServletContext that it is running in. Before destruction of the bean instance, the Servlet destroy will be called. Note that this post-processor does not support Servlet initialization parameters. Bean instances that implement the Servlet interface are supposed to be configured like any other Spring bean, that is, through constructor arguments or bean properties. For reuse of a Servlet implementation in a plain Servlet container and as a bean in a Spring context, consider deriving from Spring's HttpServletBean base class that applies Servlet initialization parameters as bean properties, supporting both the standard Servlet and the Spring bean initialization style. Alternatively, consider wrapping a Servlet with Spring's ServletWrappingController. This is particularly appropriate for existing Servlet classes, allowing to specify Servlet initialization parameters etc.
3.示例
参考:
spring bean生命周期管理
spring 源码分析之BeanPostProcessor的更多相关文章
- spring源码分析系列 (2) spring拓展接口BeanPostProcessor
Spring更多分析--spring源码分析系列 主要分析内容: 一.BeanPostProcessor简述与demo示例 二.BeanPostProcessor源码分析:注册时机和触发点 (源码基于 ...
- Spring源码分析——BeanFactory体系之抽象类、类分析(二)
上一篇分析了BeanFactory体系的2个类,SimpleAliasRegistry和DefaultSingletonBeanRegistry——Spring源码分析——BeanFactory体系之 ...
- 【Spring源码分析】Bean加载流程概览
代码入口 之前写文章都会啰啰嗦嗦一大堆再开始,进入[Spring源码分析]这个板块就直接切入正题了. 很多朋友可能想看Spring源码,但是不知道应当如何入手去看,这个可以理解:Java开发者通常从事 ...
- 【Spring源码分析】非懒加载的单例Bean初始化过程(上篇)
代码入口 上文[Spring源码分析]Bean加载流程概览,比较详细地分析了Spring上下文加载的代码入口,并且在AbstractApplicationContext的refresh方法中,点出了f ...
- 【Spring源码分析】非懒加载的单例Bean初始化过程(下篇)
doCreateBean方法 上文[Spring源码分析]非懒加载的单例Bean初始化过程(上篇),分析了单例的Bean初始化流程,并跟踪代码进入了主流程,看到了Bean是如何被实例化出来的.先贴一下 ...
- 【Spring源码分析】非懒加载的单例Bean初始化前后的一些操作
前言 之前两篇文章[Spring源码分析]非懒加载的单例Bean初始化过程(上篇)和[Spring源码分析]非懒加载的单例Bean初始化过程(下篇)比较详细地分析了非懒加载的单例Bean的初始化过程, ...
- 【spring源码分析】IOC容器初始化(一)
前言:spring主要就是对bean进行管理,因此IOC容器的初始化过程非常重要,搞清楚其原理不管在实际生产或面试过程中都十分的有用.在[spring源码分析]准备工作中已经搭建好spring的环境, ...
- 【spring源码分析】IOC容器初始化(七)
前言:在[spring源码分析]IOC容器初始化(六)中分析了从单例缓存中加载bean对象,由于篇幅原因其核心函数 FactoryBeanRegistrySupport#getObjectFromFa ...
- Spring 源码分析之 bean 依赖注入原理(注入属性)
最近在研究Spring bean 生命周期相关知识点以及源码,所以打算写一篇 Spring bean生命周期相关的文章,但是整理过程中发现涉及的点太多而且又很复杂,很难在一篇文章中把Spri ...
随机推荐
- RHEL6.5及Win7的和谐共处(投机版)
背景: 在Windows XP存在时,装了个RHEL6.5,用的是安装程序自带的Grub,后来将XP删除后重装了Windows7,RHEL的Grub被覆盖,启动不了RHEL了,于是补上RHEL的引导… ...
- jsti 和EL用法注意点
今天使用stl 结合El做jsp页面展现,出现了个问题,怎么调也调不好,最后将jstl的源码拿来跟踪调了一下才明白其中的道理. 在使用jstl tag <c:forEach var=" ...
- php CLI 模式下的传参方法
在CLI模式(命令行界面 Command Line Interface)下,传入参数有如下3种方法: 一. getopt函数(PHP 4 >= 4.3.0, PHP 5) getopt - 从命 ...
- 使用Axure来仿真Vogue网站
用户体验包括三部分:用户研究.视觉设计和交互设计.按顺序进行,在用户研究和视觉设计之后,开始交互设计,Axure是最好的交互设计的软件. Vogue是著名的奢侈品品牌,网站设计“高大上”,用Axure ...
- 大数据存储:MongoDB实战指南——常见问题解答
锁粒度与并发性能怎么样? 数据库的读写并发性能与锁的粒度息息相关,不管是读操作还是写操作开始运行时,都会请求相应的锁资源,如果请求不到,操作就会被阻塞.读操作请求的是读锁,能够与其它读操作共享,但是当 ...
- JDBC数据类型
JDBC数据类型 JDBC驱动程序Java数据类型转换到适当的JDBC类型然后再将它发送到数据库.它使用默认的大多数数据类型映射.例如,一个Java int转换成一个SQL INTEGER.创建默认映 ...
- Ubuntu 下安装Mysql 需要注意的地方.
安装卸载 sudo apt-get autoremove --purge mysql-server-5.0sudo apt-get remove mysql-serversudo apt-get au ...
- Emberjs之ComputedProperty
计算属性,以下简称CP.简单概括来讲,就是在需要属性值的时候计算一个Function,并将Function返回的值保存在属性中,当第二次获取属性值时,如果发现属性并未改变则直接读取属性,如果属性依赖的 ...
- __defineGetter__ && __defineSetter__
看别人源码碰到的,做个备忘. //针对对象增加get\set方法,返回绑定函数的返回值 Date.prototype.__defineGetter__('getYear', function() {r ...
- Java虚拟机13:互斥同步、锁优化及synchronized和volatile
互斥同步 互斥同步(Mutual Exclusion & Synchronization)是常见的一种并发正确性保证手段.同步是指子啊多个线程并发访问共享数据时,保证共享数据在同一时刻只能被一 ...