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

        com.portal.listener.StartupListener
    

注意的是,如果你使用了spring的mvc,那么原来的

		
			org.springframework.web.context.ContextLoaderListener
		
	 

就要去掉,否则会报multipul ContextLoaderListener,因为这个是继承了ContextLoaderListener的.
然后就是使用了,在你的filter里通过:
StartupListener.getBean("beanname");

你可能感兴趣的:(Bean,Spring,Web,XML,MVC)