因为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);
代码:
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);