前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring核心——官配后置处理器 原

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

作者头像
随风溜达的向日葵
发布2018-08-15 11:18:26
4100
发布2018-08-15 11:18:26
举报
文章被收录于专栏:技术墨客技术墨客

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

RequiredAnnotationBeanPostProcessor

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

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

代码语言:javascript
复制
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
<!-- 其他bean -->

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

使用方法2,设置context:

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

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

代码语言:javascript
复制
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
   <property name="requiredAnnotationType" value="x.y.Require" />
</bean>
代码语言:javascript
复制
package x.y;

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

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

代码语言:javascript
复制
<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中的属性方法:

代码语言:javascript
复制
<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继承自它。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • RequiredAnnotationBeanPostProcessor
  • AutowiredAnnotationBeanPostProcessor
  • CommonAnnotationBeanPostProcessor
  • InitDestroyAnnotationBeanPostProcessor
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档