如何为应用程序上下文初始化事件添加一个钩子? [英] 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.
在 Spring 3(如果你使用这个版本)中,ApplicationListener
类是通用的,你可以声明你感兴趣的事件类型,事件会被相应地过滤.您可以像这样简化 bean 代码:
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屋!