你的位置:首页 > Java教程

[Java教程]如何在Java Filter 中注入 Service


在项目中遇到一个问题,在 Filter中注入 Serivce失败,注入的service始终为null。如下所示:

public class WeiXinFilter implements Filter{    @Autowired  private UsersService usersService;

在 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 方法中使用 usersService 时报空指针异常。

解决方法:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {    HttpServletRequest req = (HttpServletRequest)request;    HttpServletResponse resp = (HttpServletResponse)response;        = (                getWebApplicationContext(req.getSession().getServletContext());        if(context != null && context.getBean("usersService") != null && usersService == null)          usersService = (UsersService) context.getBean("usersService");         Users users = this.usersService.queryByOpenid(openid);

这样就行了。