如何在应用程序上下文初始化事件中添加一个钩子? [英] How to add a hook to the application context initialization event?
问题描述
对于普通的Servlet,我想您可以声明上下文侦听器 ,但对于Spring MVC,Spring会让这变得更容易吗?
For a regular Servlet, I guess you could declare a context listener, but for Spring MVC would Spring make this any easier?
此外,如果我定义了上下文侦听器,然后需要访问在我的servlet.xml
或applicationContext.xml
中定义的bean,我将如何访问它们?
Furthermore, if I define a context listener and then would need to access the beans defined in my servlet.xml
or applicationContext.xml
, how would I get access to them?
推荐答案
为此,您必须创建并注册一个实现ApplicationListener
接口的bean,如下所示:
To do that, you must create and register a bean that implements the ApplicationListener
interface, something like this:
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:
You then register this bean within your servlet.xml
or applicationContext.xml
file:
<bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />
,当应用程序上下文初始化时,Spring会通知它.
and Spring will notify it when the application context is initialized.
In Spring 3 (if you are using this version), the ApplicationListener
class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:
public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
// now you can do applicationContext.getBean(...)
// ...
}
}
这篇关于如何在应用程序上下文初始化事件中添加一个钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!