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

Spring的Ioc容器依赖后置处理器实现多种功能,本文聚焦于RequiredAnnotationBeanPostProcessor、AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor和InitDestroyAnnotationBeanPostProcessor。这些处理器分别处理@Required、@Autowired、@PostConstruct、@PreDestroy等注解,用于参数检查、自动装配、生命周期管理和资源注入。了解并掌握这些处理器的用法和配置技巧,对于提升Spring应用的开发和维护能力至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

RequiredAnnotationBeanPostProcessor

RequiredAnnotationBeanPostProcessor它用于处理@Required注解。当我们一个Setter方法加入@Required后,表示必须设置参数,如果未设置则抛出BeanInitializationException异常。欢迎大家加入659270626来交流学习,进群还可领架构资料。

使用方法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继承自它。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值