Spring Event Listener

Spring Event Listener

1. 背景:

因为系统业务需要, 系统要与短信服务提供商梦网进行对接, 并且不直接使用梦网提供的sdk(可以自己对发送请求的线程进行更加细粒度的控制), 所以使用Retrofit对接梦网的api, 但是梦网的api url是配置在数据库中的, 所以在初始化Retrofit的时候不能通过Repository(数据层)读到数据库配置的url(因为Retrofit的初始化是在Configuration中的, Configuration的创建周期在Repository之前, 在Retrofit初始化的时候Repository还没有初始化). 因此就要手动创建Retrofit的bean, 并将其加入到spring context中.

2. Spring中关于context的4个event

在spring中有4个event是关于spring context的生命周期的

  • ContextStartedEvent

    明确调用ConfigurableApplicationContext.start()才会触发. 在spring boot中可以使用如下方法触发

        @SpringBootApplication
        public class DemoApplication {
        
            public static void main(String[] args) {
                SpringApplication.run(DemoApplication.class, args).start();
            }
        }
    
  • ContextRefreshedEvent:

    ApplicationContext初始化结束或者刷新的时候触发. 这里的初始化结束是指所有的bean已经加载完毕, post-processor bean被激活, 单例bean被初始化, 同时ApplicationContext对象可以被使用了.
    也可以明确调用refresh()方法触发. 但是要注意, 并不是所有的ApplicationContext实例都支持hot refresh的, 比如GenericApplicationContext是不支持hot refresh的, 所以Spring boot中如果直接调用

        SpringApplication.run(DemoApplication.class, args).refresh();
    

    就会报

    Exception in thread "main" java.lang.IllegalStateException: GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once
    

    错误, 因为Spring boot中的ApplicationContext实例是AnnotationConfigEmbeddedWebApplicationContext, 是继承于GenericApplicationContext的. 但是XmlWebApplicationContext就是支持hot refresh

  • ContextStoppedEvent

    可以通过调用ConfigurableApplicationContext.stop()触发. 当ApplicationContext调用了stop()之后, 可以重新调用start()启动context.

  • ContextClosedEvent

    ApplicationContextclose时触发, 可以手动调用close()方法或者直接退出应用来触发.

另外Bean也可以响应spring bean lifecycle中的start和close阶段, 例如:

    // Animal 是一个bean

    public class Animal{

        // start event invoke
        @PostConstruct
        public void start() throws Exception {
            System.out.println("start");
        }
    
        // close event invoke
        @PreDestroy
        public void destroy() throws Exception {
            System.out.println("destroy");
        }
    }

3. 解决方法

有了上述的知识背景, 解决当下的问题就很简单了, 因为我们是需要自己创建bean并且加入到ApplicationContext中, 所以选择ContextRefreshedEvent

注意: 下述代码只是为了表现一个思路, 和实际代码有出入

@Component
public class ApplicationContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
            // 获取BeanFactory
        ConfigurableListableBeanFactory beanFactory = ((GenericApplicationContext) event.getApplicationContext()).getBeanFactory();
        // 手动注入singleton  scope 的bean
        beanFactory.registerSingleton(MontnetsApi.class.getSimpleName(), montnetsApiBuilder.builder());
    }
}
@Component
public class MontnetsApiBuilder extends AbstractSmsVendorApiBuilder<MontnetsApi> {

    @Autowired
    private SmsVendorRegistry smsVendorRegistry;

    /**
     * 构建梦网API
     */
    @Override
    public MontnetsApi build() {
        // 调用SmsVendorRegistry查找梦网url, 创建Retrofit接口
    }
}

因为MontnetsApi是手动注入的, 所以在ApplicationContext初始化完成触发ContextRefreshedEvent的时候context中还没有MontnetsApi这个bean, 所以在使用这个bean的地方要特殊处理一下

@Service
@Validated
public class MontnetsSmsSenderService extends AbstractSmsSenderService {

     // 用到MontnetsApi的地方都要使用懒式加载
    @Autowired(required = false)
    @Lazy
    private MontnetsApi montnetsApi;
    
    ...
    other code
    ...
}

4. 总结

spring框架可以说是开发java web项目必备框架, 了解spring中的一些基础知识点, 例如listener, spring bean lifecycle, spring aop, spring中各种bean的加载顺序等是很有必要, 如果不了解这些知识点, 在解决一些问题的时候就会无从下手. 需要花大量的时间和精力去了解才能把问题解决.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容