首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

从Filter中失去Spring的ApplicationContext

2012-10-30 
从Filter中得到Spring的ApplicationContext因为Filter是在ApplicationContext之外运行的,它们不能直接inje

从Filter中得到Spring的ApplicationContext
因为Filter是在ApplicationContext之外运行的,它们不能直接inject其他的Bean到Filter对象中。使用其他的Bean,Filter需要通过ServletContext,得到Spring的ApplicationContext。Spring提供了WebApplicationContextUtils的getWebApplicationContext来方便获取。
代码:
public void doFilter(ServletRequest req, ServletResponse rep,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
ApplicationContext ac              =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
User user = (User)ac.getBean("user1");
System.out.println(user.getId());
}

对不起 ,以上得到的ApplicationContext 是新的。如下则可以
ServletContext  servletContext  =config.getServletContext();
ap= (WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

热点排行