前言: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 - 优快云博客
https://blog.youkuaiyun.com/xiakepan/article/details/49074023
本文介绍了解决在Filter中使用Spring框架注入Service类的问题。通过在Filter的init()方法中获取ServletContext,并利用WebApplicationContextUtils从上下文中获取Bean,成功实现了Service的注入。

被折叠的 条评论
为什么被折叠?



