如何在应用程序上下文初始化事件中添加一个钩子? [英] How to add a hook to the application context initialization event?

查看:60
本文介绍了如何在应用程序上下文初始化事件中添加一个钩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于普通的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.xmlapplicationContext.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.xmlapplicationContext.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(如果您使用的是此版本)中,

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆