当前位置: 代码迷 >> Java相关 >> 怎么在Java Filter 中注入 Service
  详细解决方案

怎么在Java Filter 中注入 Service

热度:20   发布时间:2016-04-22 19:47:55.0
如何在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;                XmlWebApplicationContext context = (XmlWebApplicationContext)WebApplicationContextUtils.
                getWebApplicationContext(req.getSession().getServletContext());
if(context != null && context.getBean("usersService") != null && usersService == null) usersService = (UsersService) context.getBean("usersService");         Users users = this.usersService.queryByOpenid(openid);

这样就行了。

 

  相关解决方案