正确实现用spring扫描自定义的annotation
背景
在使用spring时,有时候有会有一些自定义annotation的需求,比如一些Listener的回调函数。
比如:
@Service
public class MyService {
@MyListener
public void onMessage(Message msg){
}
}
一开始的时候,我是在Spring的ContextRefreshedEvent事件里,通过context.getBeansWithAnnotation(Component.class) 来获取到所有的bean,然后再检查method是否有@MyListener的annotation。
后来发现这个方法有缺陷,当有一些spring bean的@Scope设置为session/request时,创建bean会失败。
参考:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes
在网上搜索了一些资料,发现不少人都是用context.getBeansWithAnnotation(Component.class),这样子来做的,但是这个方法并不对。
BeanPostProcessor接口
后来看了下spring jms里的@JmsListener的实现,发现实现BeanPostProcessor接口才是最合理的办法。
public interface BeanPostProcessor {
/**
* Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0). The
* post-processor can decide whether to apply to either the FactoryBean or created
* objects or both through corresponding {@code bean instanceof FactoryBean} checks.
* <p>This callback will also be invoked after a short-circuiting triggered by a
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
* in contrast to all other BeanPostProcessor callbacks.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
所有的bean在创建完之后,都会回调postProcessAfterInitialization函数,这时就可以确定bean是已经创建好的了。
所以扫描自定义的annotation的代码大概是这个样子的:
public class MyListenerProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
if (methods != null) {
for (Method method : methods) {
MyListener myListener = AnnotationUtils.findAnnotation(method, MyListener.class);
// process
}
}
return bean;
}
}
SmartInitializingSingleton 接口
看spring jms的代码时,发现SmartInitializingSingleton 这个接口也比较有意思。
就是当所有的singleton的bean都初始化完了之后才会回调这个接口。不过要注意是 4.1 之后才出现的接口。
public interface SmartInitializingSingleton {
/**
* Invoked right at the end of the singleton pre-instantiation phase,
* with a guarantee that all regular singleton beans have been created
* already. {@link ListableBeanFactory#getBeansOfType} calls within
* this method won't trigger accidental side effects during bootstrap.
* <p><b>NOTE:</b> This callback won't be triggered for singleton beans
* lazily initialized on demand after {@link BeanFactory} bootstrap,
* and not for any other bean scope either. Carefully use it for beans
* with the intended bootstrap semantics only.
*/
void afterSingletonsInstantiated();
}
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/SmartInitializingSingleton.html
正确实现用spring扫描自定义的annotation的更多相关文章
- spring扫描自定义注解并进行操作
转载:http://blog.csdn.net/cuixuefeng1112/article/details/45331233 /** * 扫描注解添加服务到缓存以供判断时候为对外开放service ...
- spring AOP自定义注解方式实现日志管理
今天继续实现AOP,到这里我个人认为是最灵活,可扩展的方式了,就拿日志管理来说,用Spring AOP 自定义注解形式实现日志管理.废话不多说,直接开始!!! 关于配置我还是的再说一遍. 在appli ...
- spring AOP自定义注解 实现日志管理
今天继续实现AOP,到这里我个人认为是最灵活,可扩展的方式了,就拿日志管理来说,用Spring AOP 自定义注解形式实现日志管理.废话不多说,直接开始!!! 关于配置我还是的再说一遍. 在appli ...
- springboot扫描自定义的servlet和filter代码详解_java - JAVA
文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 这几天使用spring boot编写公司一个应用,在编写了一个filter,用于指定编码的filter,如下: /** ...
- 利用Spring AOP自定义注解解决日志和签名校验
转载:http://www.cnblogs.com/shipengzhi/articles/2716004.html 一.需解决的问题 部分API有签名参数(signature),Passport首先 ...
- spring中自定义Event事件的使用和浅析
在我目前接触的项目中,用到了许多spring相关的技术,框架层面的spring.spring mvc就不说了,细节上的功能也用了不少,如schedule定时任务.Filter过滤器. intercep ...
- Spring 扫描标签<context:component-scan/>
一. <context:annotation-config/> 此标签支持一些注入属性的注解, 列如:@Autowired, @Resource注解 二. <context:comp ...
- 6.2 dubbo在spring中自定义xml标签源码解析
在6.1 如何在spring中自定义xml标签中我们看到了在spring中自定义xml标签的方式.dubbo也是这样来实现的. 一 META_INF/dubbo.xsd 比较长,只列出<dubb ...
- 6.1 如何在spring中自定义xml标签
dubbo自定义了很多xml标签,例如<dubbo:application>,那么这些自定义标签是怎么与spring结合起来的呢?我们先看一个简单的例子. 一 编写模型类 package ...
随机推荐
- Python基础之常用模块
一.time模块 1.时间表达形式: 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: 1.1.时间戳(timestamp) :通常来说,时间 ...
- PDF文件怎么修改,PDF文件编辑方法
PDF文件是一种独特的文件,在日常办公中已经成为我们使用最广泛的电子文档格式.在使用PDF文件中会遇到PDF文件有错区的时候,再从新制作一个PDF文件会比较麻烦,只能通过工具来对PDF文件进行修改,这 ...
- 饮冰三年-人工智能-linux-01通过VM虚拟机安装contes系统
先决条件:VM虚拟机的安装.contes系统的镜像文件 1:创建新的虚拟机 2:下一步,稍后安装操作系统 3:选择对应的系统 4:选择对应的路径 至此虚拟机已经创建完成(相当于买了一台新电脑) 5:编 ...
- python列表1
List (列表)List(列表) 是 Python 中使用最 频繁的数据类 型.列表 可以 完成大 多数集 合类 的数据 结构 实现. 列表中 元素 的类型 可以 不相同 ,它支 持数 字,字 符串 ...
- JAVA 数据类型数组
普通int: public class Array { //成员变量 private int[] data; private int size; //构造函数,传入数组的容量capacity构造Arr ...
- Facebook的React Native之所以能打败谷歌的原因有7个(ReactNative vs Flutter)
https://baijiahao.baidu.com/s?id=1611028483072699113&wfr=spider&for=pc 如果你喜欢用(或希望能够用)模板搭建应用, ...
- Git基础(三) 跟踪文件
检查当前文件状态 git status 跟踪新文件 git add README 状态简览 git status -s 或 git status --short 忽略文件 创建一个名为.gitigno ...
- zookeeper都有哪些使用场景
分布式协调 这个其实是zk很经典的一个用法,比如,A系统发送个请求到mq,然后B拿到消息消费之后处理了.那A系统如何知道B系统的处理结果? 用zk就可以实现分布式系统之间的协调工作.A系统发送请求之后 ...
- [转] js中的钩子机制(hook)
什么是钩子机制?使用钩子机制有什么好处? 钩子机制也叫hook机制,或者你可以把它理解成一种匹配机制,就是我们在代码中设置一些钩子,然后程序执行时自动去匹配这些钩子:这样做的好处就是提高了程序的执行效 ...
- 去除ArrayList集合中的重复自定义对象元素
要求去除ArrayList集合中重复的Student的对象(什么叫重复,所有属性值都相同叫做重复). 思路: 1.创建一个新集合 2.遍历旧集合中的每一个元素,去新集合中找这个元素,如果这个元素不存在 ...