在action,servlet之外的bean里获取applicationcontext的方法

本文介绍了一种在Spring框架中通过监听器获取ApplicationContext的方法,并展示了如何在web容器启动时使用这种方式初始化数据。
1.通过Spring提供的工具类获取ApplicationContext对象 
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class InitServletContextListener implements ServletContextListener {
private static WebApplicationContext springContext;
    public InitServletContextListener() {
        super();
    }  
    public void contextInitialized(ServletContextEvent event) {
        springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
    } 
    public void contextDestroyed(ServletContextEvent event) {
    }
    public static ApplicationContext getApplicationContext() {
        return springContext;
    } 
}
2.将继承该监听器接口的类配置到web.xml文件中:
<!-- 用于初始化数据的监听器 -->
<listener>
<listener-class>包名.InitServletContextListener</listener-class>
</listener>
获取时
InitServletContextListener.getApplicationContext().getBean("testService");
3.另外,在web容器启动时初始化数据:
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class InitServletContextListener implements ServletContextListener {
/** 
* 当Servlet 容器启动Web 应用时调用该方法。在调用完该方法之后,容器再对Filter 初始化, 
* 并且对那些在Web 应用启动时就需要被初始化的Servlet 进行初始化。 
*/ 
public void contextInitialized(ServletContextEvent sce) {
/*获取ServletContext对象*/ 
ServletContext application = sce.getServletContext();
// 得到Service的实例对象
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(application);
PrivilegeService testService = (PrivilegeService) ac.getBean("testService");
List<?> testList = testService.findAll();
application.setAttribute("testList", testList);
}
/** 
* 当Servlet 容器终止Web 应用时调用该方法。在调用该方法之前,容器会先销毁所有的Servlet 和Filter 过滤器。 
*/
public void contextDestroyed(ServletContextEvent sce) {
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值