SpringBoot启动后获取特定注解的Bean实例代码(转)-观察者模式

来自:https://zhuanlan.zhihu.com/p/375973197

本文研究的主要是Spring启动后获取所有拥有特定注解的Bean,具体如下。

最近项目中遇到一个业务场景,就是在Spring容器启动后获取所有的Bean中实现了一个特定接口的对象,第一个想到的是ApplicationContextAware,在setApplicationContext中去通过ctx获取所有的bean,后来发现好像逻辑不对,这个方法不是在所有bean初始化完成后实现的,后来试了一下看看有没有什么Listener之类的,发现了好东西ApplicationListener,然后百度一下ApplicationListener用法,原来有一大堆例子,我也记录一下我的例子好了。

很简单,只要实现ApplicationListener<ContextRefreshedEvent>接口,然后把实现类进行@Component即可,代码如下:

自定义标签:

/**
 * @Author: Q
 * @Date: 2021/4/30 17:07
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Dev {
    @AliasFor(
            annotation = Component.class
    )
    String value() default "";
}

 

 

目标类1:

@Dev
public class ******ServiceImpl

 

 注意,这个事件是在@PostContruct之后的!,所以这里得到的bean不能在@PostContruct方法中调用

/**
 * 启动后加载指定bean ,注意,这个是在@PostContruct之后的!
 * @Author: Q
 * @Date: 2021/5/28 10:33
 */
@Component
public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 根容器为Spring容器
        if(event.getApplicationContext().getParent()==null){
            Map<String,Object> beans = event.getApplicationContext().getBeansWithAnnotation(Dev.class);
            for (Object bean:beans.values()){
                System.err.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+bean==null?"null":bean.getClass().getName());
            }
            System.err.println("=====ContextRefreshedEvent====="+event.getSource().getClass().getName());
        }
    }
}

 

其中,通过event.getApplicationContext().getBeansWithAnnotation获取到所有拥有特定注解的Beans集合,然后遍历所有bean实现业务场景。

打印如下:

2021-05-28 11:41:31.152  INFO 26104 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
com.***.***.***.service.dict.impl.******ServiceImpl$$EnhancerBySpringCGLIB$$2c7ea6b8
com.***.***.***.service.dict.impl.******ServiceImpl$$EnhancerBySpringCGLIB$$2a000d9b
=====ContextRefreshedEvent=====org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext

 

总结思考:这样的功能可以实现系统参数的初始化,获取系统中所有接口服务清单等一系列需要在Spring启动后初始化的功能。

延生一下:除了以上启动后事件外,还有其他三个事件

Closed在关闭容器的时候调用,Started理论上在容器启动的时候调用,Stopped理论上在容器关闭的时候调用。

posted @ 2023-04-12 16:36  Mars.wang  阅读(630)  评论(0)    收藏  举报