spring在filter中注入bean

由于filter不属于spring容器管理,所以filter内不能注入bean;为解决此问题我们写了个listener,在web启动时将spring context丢进去.这样就可以从filter里拿到我们想要的bean了.
public class StartupListener extends ContextLoaderListener implements
ServletContextListener {

protected Logger log = LoggerFactory
.getLogger(StartupListener.class);

public void contextInitialized(ServletContextEvent event){

if (log.isDebugEnabled()) {
log.debug("initializing context...");
}

// call Spring's context ContextLoaderListener to initialize
// all the context files specified in web.xml
super.contextInitialized(event);

ServletContext context = event.getServletContext();
setServletContext(context);

ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(context);
setAppContext(ctx);

setupContext(context);
}

public static void setupContext(ServletContext context) {

}

public static Object getBean(String beanName) {
return appContext.getBean(beanName);
}

/**
*/
private static ApplicationContext appContext;

public static ApplicationContext getAppContext() {
return appContext;
}

public static void setAppContext(ApplicationContext ctx) {
appContext = ctx;
}

/**
* ServletContext
*/
private static ServletContext servletContext;

/**
* @return Returns the servletContext.
*/
public static ServletContext getServletContext() {
return servletContext;
}

/**
* @param servletContext
* The servletContext to set.
*/
public static void setServletContext(ServletContext servletContext) {
StartupListener.servletContext = servletContext;
}

public static String getServletWebInfRealPath() {
return servletContext.getRealPath("WEB-INF");
}

}

web.xml
<listener>
<listener-class>com.portal.listener.StartupListener</listener-class>
</listener>

注意的是,如果你使用了spring的mvc,那么原来的
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

就要去掉,否则会报multipul ContextLoaderListener,因为这个是继承了ContextLoaderListener的.
然后就是使用了,在你的filter里通过:
StartupListener.getBean("beanname");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值