我们在使用Spring开发的时候,很多的时候都需要在bean初始化之前,预先处理一些基础性东西,如从配置服务器上获取服务启动配置参数,但是我们往往是在初始化类上使用@postConstruct或是init-method="init"。但是这两种方法,我们很难控制执行的先后顺序,为了控制绝对的初始化顺序,所以我们需要使用ApplicationListener,这个类可以使用org.springframework.context.event包下面的所有事件,我们可以使用ContextRefreshedEvent来保证绝对的第一个执行
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class ApplicationListenerImp implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
System.out.println("aaa");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("bbb");
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.senyint.framework.common.ApplicationContextUtil;
import com.senyint.framework.config.SpringContext;
import com.senyint.framework.controller.DemoController;
import com.senyint.framework.controller.DyController;
public class Demo5 {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac=ApplicationContextUtil.getContext();
ac.register(DyController.class);
//System.out.println(ac.containsBean("applicationListenerImp"));
/*
* DemoService demoService=SpringContext.getBean(DemoService.class);
* System.out.println(demoService.getInfo()); ApplicationContext
* context=SpringContext.getContext(); DemoService
* demoService1=context.getBean(DemoService.class);
* System.out.println(demoService1.getInfo());
*/
System.out.println(ac.containsBean("demoController"));
ac.removeBeanDefinition("demoController");
System.out.println(ac.containsBean("demoController"));
testDyBean(ac);
}
public static void testDyBean(AnnotationConfigApplicationContext ac) {
System.out.println(ac.containsBean("dyController"));
DyController dy=ac.getBean(DyController.class);
System.out.println(dy.getInfo());
}
}
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
aaa
bbb
true
false
true
this is a test
下面是执行结果,是不是很明显。