关于spring上下文,springmvc上下文区别请读者自己百度哦。
filter中获取spring的上下文
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
ServletContext servletContext = filterConfig.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
}
而如何获取spring-mvc的上下文呢,原因使我想在filter中调取service接口,查了一圈没找到,最终debug找到一个很丑的方式,如下:
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
//临时方案,获取spring-Mvc上下文
WebApplicationContext wctx = (WebApplicationContext) request.getSession().getServletContext()
.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet");
authorizationService = (AuthorizationService)wctx.getBean(AuthorizationService.class);
wxAppLoginService = (WxAppLoginService)wctx.getBean(WxAppLoginService.class);
......
chain.doFilter(request, response);
}
重点就在于"org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet"
通过这个getAttribute就可以拿到springMvc的上下文,就可以使用spring-servlet里的服务bean了。