由于filter不属于spring容器管理,所以filter内不能注入bean;为解决此问题我们写了个listener,在web启动时将spring context丢进去.这样就可以从filter里拿到我们想要的bean了.
web.xml
注意的是,如果你使用了spring的mvc,那么原来的
就要去掉,否则会报multipul ContextLoaderListener,因为这个是继承了ContextLoaderListener的.
然后就是使用了,在你的filter里通过:
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");