zoukankan      html  css  js  c++  java
  • 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。例:

     ConfigurableBeanFactory.addBeanPostProcessor(org.springframework.beans.factory.config.BeanPostProcessor),

    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生命周期管理

  • 相关阅读:
    构造函数、原型、实例化对象
    JS闭包的理解
    JQuery知识点
    面向对象
    学习使用Vuex
    Runtime详解
    ffmpeg各结构体之间关联 ---- AVPacket
    AVFrame
    block的底层原理
    performSelector
  • 原文地址:https://www.cnblogs.com/davidwang456/p/5633586.html
Copyright © 2011-2022 走看看