美文网首页
Spring核心——官配后置处理器

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

作者: 零点145 | 来源:发表于2019-07-10 12:35 被阅读0次

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

RequiredAnnotationBeanPostProcessor

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

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

<!-- 其他bean -->

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

使用方法2,设置context:

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

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

packagex.y;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public@interfaceRequire {}

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

AutowiredAnnotationBeanPostProcessor

这个后置处理器在3.x之后使用Spring框架的系统几乎都会使用,就是他在处理大名鼎鼎的@Autowired和@Value注解。此外他也支持JSR-330中的@Inject注解。当我们使用

或时,IoC容器也会启用这个功能。

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

CommonAnnotationBeanPostProcessor

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

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

InitDestroyAnnotationBeanPostProcessor

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

相关文章

网友评论

      本文标题:Spring核心——官配后置处理器

      本文链接:https://www.haomeiwen.com/subject/snockctx.html