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

全文共 557 个字

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

RequiredAnnotationBeanPostProcessor

官方的一些功能就是用后置处理器的方式实现的,例如RequiredAnnotationBeanPostProcessor,它用于处理@Required注解。当我们一个Setter方法加入@Required后,表示必须设置参数,如果未设置则抛出BeanInitializationException异常。

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

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

这相当于直接添加一个后置处理器,他会检查所有的被@Required标注的Setter方法。

使用方法2,设置context:

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

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

<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方法:

<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容器也会启用这个功能。

可以通过setAutowiredAnnotationType、setAutowiredAnnotationTypes方法设定对应的注解,可以通过setRequiredParameterName来设置@Autowired中的属性方法:

<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继承自它。