java listen to ContextRefreshedEvent

落花浮王杯 提交于 2019-12-03 06:12:23

A ContextRefreshEvent occurs

when an ApplicationContext gets initialized or refreshed.

so you are on the right track.

What you need to do is declare a bean definition for classX.

Either with @Component and a component scan over the package it's in

@Component
public classX implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
       //do something if all apps have initialised
    }
}

or with a <bean> declaration

<bean class="some.pack.classX"></bean>

Spring will detect that the bean is of type ApplicationListener and register it without any further configuration.


Just FYI, Java has naming conventions for types, variables, etc. For classes, the convention is to have their names start with an uppercase alphabetic character.

Spring >= 4.2

You can use annotation-driven event listener as below :

@Component
public class classX  {

    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {

    }
}

the ApplicationListener you want to register is defined in the signature of the method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!