Spring核心——官配后置处理器

实际上Ioc容器中的大量功能都是经过后置处理器实现的,这里介绍几个主要的处理器。java

RequiredAnnotationBeanPostProcessor

RequiredAnnotationBeanPostProcessor它用于处理@Required注解。当咱们一个Setter方法加入@Required后,表示必须设置参数,若是未设置则抛出BeanInitializationException异常。node

使用方法1,直接添加一个Bean:spring

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
<!-- 其余bean -->

这至关于直接添加一个后置处理器,他会检查全部的被@Required标注的Setter方法。框架

使用方法2,设置context:ui

<!-- 若是使用了如下2个context级别的标签,则会启用RequiredAnnotationBeanPostProcessor的功能 -->
<context:annotation-config />
<context:component-scan />

使用技巧1,修改扫描的注解。处理器默认会识别@Required注解,可是能够经过RequiredAnnotationBeanPostProcessor::setRequiredAnnotationType修改生效的注解,例如:spa

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
   <property name="requiredAnnotationType" value="x.y.Require" />
</bean>
package x.y;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Require {}

使用技巧2,告知RequiredAnnotationBeanPostProcessor不处理某些Bean方法:code

<bean class="x.y.A">
    <meta  key="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.skipRequiredCheck" value="true" /> 
</bean>

AutowiredAnnotationBeanPostProcessor

这个后置处理器在3.x以后使用Spring框架的系统几乎都会使用,就是他在处理大名鼎鼎的@Autowired和@Value注解。此外他也支持JSR-330中的@Inject注解。当咱们使用<context:annotation-config />
或<context:component-scan />时,IoC容器也会启用这个功能。component

能够经过setAutowiredAnnotationType、setAutowiredAnnotationTypes方法设定对应的注解,能够经过setRequiredParameterName来设置@Autowired中的属性方法:xml

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
   <property name="autowiredAnnotationType" value="x.y.MyInjectAnnotation" />
</bean>

CommonAnnotationBeanPostProcessor

这个处理器继承InitDestroyAnnotationBeanPostProcessor实现JSR-250的@PostConstruct和@PreDestroy的处理,此外还支持@Resource注解。JSR-250和Resouce貌似没有什么太直接的关系,因此被命名为Common表示这是一个大杂烩通常的存在。一样使用annotation-config和component-scan会被自动启用(由于都是用于处理注解的)。继承

一样也有initAnnotationType、destroyAnnotationType等Setter方法来设置自定义注解。

InitDestroyAnnotationBeanPostProcessor

处理Bean的生命周期方法以及资源数据注入,CommonAnnotationBeanPostProcessor继承自它。

 

个人博客即将搬运同步至腾讯云+社区,邀请你们一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=18cvzc1xnodev。

相关文章
相关标签/搜索