为此,你必须创建并注册一个实现该
ApplicationListener接口的bean,如下所示:
package test.pack.age;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationEvent;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;public class ApplicationListenerBean implements ApplicationListener { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext(); // now you can do applicationContext.getBean(...) // ... } }}然后,你在
servlet.xml或
applicationContext.xml文件中注册此bean :
<bean id="eventListenerBean" />
当应用程序上下文初始化时,Spring会通知它。
在Spring 3中(如果使用的是该版本),ApplicationListener该类是通用的,你可以声明你感兴趣的事件类型,并且事件将被相应地过滤。你可以像下面这样简化你的bean代码:
public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext applicationContext = event.getApplicationContext(); // now you can do applicationContext.getBean(...) // ... }}


