Spring Event Listener

Spring Event Listener

1. 背景:

因?yàn)橄到y(tǒng)業(yè)務(wù)需要, 系統(tǒng)要與短信服務(wù)提供商夢網(wǎng)進(jìn)行對接, 并且不直接使用夢網(wǎng)提供的sdk(可以自己對發(fā)送請求的線程進(jìn)行更加細(xì)粒度的控制), 所以使用Retrofit對接夢網(wǎng)的api, 但是夢網(wǎng)的api url是配置在數(shù)據(jù)庫中的, 所以在初始化Retrofit的時(shí)候不能通過Repository(數(shù)據(jù)層)讀到數(shù)據(jù)庫配置的url(因?yàn)镽etrofit的初始化是在Configuration中的, Configuration的創(chuàng)建周期在Repository之前, 在Retrofit初始化的時(shí)候Repository還沒有初始化). 因此就要手動創(chuàng)建Retrofit的bean, 并將其加入到spring context中.

2. Spring中關(guān)于context的4個event

在spring中有4個event是關(guān)于spring context的生命周期的

  • ContextStartedEvent

    明確調(diào)用ConfigurableApplicationContext.start()才會觸發(fā). 在spring boot中可以使用如下方法觸發(fā)

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

    當(dāng)ApplicationContext初始化結(jié)束或者刷新的時(shí)候觸發(fā). 這里的初始化結(jié)束是指所有的bean已經(jīng)加載完畢, post-processor bean被激活, 單例bean被初始化, 同時(shí)ApplicationContext對象可以被使用了.
    也可以明確調(diào)用refresh()方法觸發(fā). 但是要注意, 并不是所有的ApplicationContext實(shí)例都支持hot refresh的, 比如GenericApplicationContext是不支持hot refresh的, 所以Spring boot中如果直接調(diào)用

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

    就會報(bào)

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

    錯誤, 因?yàn)镾pring boot中的ApplicationContext實(shí)例是AnnotationConfigEmbeddedWebApplicationContext, 是繼承于GenericApplicationContext的. 但是XmlWebApplicationContext就是支持hot refresh

  • ContextStoppedEvent

    可以通過調(diào)用ConfigurableApplicationContext.stop()觸發(fā). 當(dāng)ApplicationContext調(diào)用了stop()之后, 可以重新調(diào)用start()啟動context.

  • ContextClosedEvent

    當(dāng)ApplicationContextclose時(shí)觸發(fā), 可以手動調(diào)用close()方法或者直接退出應(yīng)用來觸發(fā).

另外Bean也可以響應(yīng)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. 解決方法

有了上述的知識背景, 解決當(dāng)下的問題就很簡單了, 因?yàn)槲覀兪切枰约簞?chuàng)建bean并且加入到ApplicationContext中, 所以選擇ContextRefreshedEvent

注意: 下述代碼只是為了表現(xiàn)一個思路, 和實(shí)際代碼有出入

@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;

    /**
     * 構(gòu)建夢網(wǎng)API
     */
    @Override
    public MontnetsApi build() {
        // 調(diào)用SmsVendorRegistry查找夢網(wǎng)url, 創(chuàng)建Retrofit接口
    }
}

因?yàn)?code>MontnetsApi是手動注入的, 所以在ApplicationContext初始化完成觸發(fā)ContextRefreshedEvent的時(shí)候context中還沒有MontnetsApi這個bean, 所以在使用這個bean的地方要特殊處理一下

@Service
@Validated
public class MontnetsSmsSenderService extends AbstractSmsSenderService {

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

4. 總結(jié)

spring框架可以說是開發(fā)java web項(xiàng)目必備框架, 了解spring中的一些基礎(chǔ)知識點(diǎn), 例如listener, spring bean lifecycle, spring aop, spring中各種bean的加載順序等是很有必要, 如果不了解這些知識點(diǎn), 在解決一些問題的時(shí)候就會無從下手. 需要花大量的時(shí)間和精力去了解才能把問題解決.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容