【Spring】【3】处理filter不能利用spring注入

前言:filter里面需要查询数据库,于是注入了service类,但是发现根本注入不了

正文:

解决方法:主要就是init()部分代码

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);
    }
}

参考博客:

filter不能利用spring注入怎么办? - Blitz_Man - CSDN博客
https://blog.csdn.net/xiakepan/article/details/49074023

原文地址:https://www.cnblogs.com/huashengweilong/p/10941514.html