问题:
写了一个filter,需要查询数据库,于是利用spring注入了service类,但是运行的时候发现,service一直是空,度娘之后发现由于种种原因,filter里面没有注入。
解决办法:
public class AppFilter implements Filter {
private AkskService akskService;//这个就是需要注入的service
public void destroy() {
}
public void doFilter(ServletRequest servletReq, ServletResponse servletRes, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletReq;
HttpServletResponse response = (HttpServletResponse) servletRes;
}
public void init(FilterConfig config) throws ServletException {
ServletContext context = config.getServletContext();//这里获取applicationContext
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
akskService = (AkskService) ctx.getBean(AkskService.class);
}
}