对于常规的Servlet,我想你可以声明一个上下文侦听器,但是对于Spring MVC,Spring可以使它更容易吗?
此外,如果定义了上下文侦听器,然后需要访问在servlet.xml或中定义的bean,我applicationContext.xml将如何访问它们?
servlet.xml
applicationContext.xml
为此,你必须创建并注册一个实现该ApplicationListener接口的bean,如下所示:
ApplicationListener
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" class="test.pack.age.ApplicationListenerBean" />
当应用程序上下文初始化时,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(...) // ... } }