
-
filter和servlet不受spring管理,所以不能依赖注入spring管理的bean,在servlet里的init 方法加入如下代码:
private XxxxService xxxxService; WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()); xxxxService= (XxxxService) wac.getBean("xxxxService");即可获得spring管理的bean.
filter代码如下:wac = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()); xxxxService= (XxxxService) wac.getBean("xxxxService"); -
如果项目任何地方都想用获取到spring bean,可以用ApplicationContextAware来实现
package bgi.genebook.vip.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class AppContextUtil implements ApplicationContextAware { private static ApplicationContext context; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context=applicationContext; } public static ApplicationContext getContext(){ return context; } }




近期评论