如何`@Autowired`非Spring类或由新X()实例化?

时间:2018-05-28 02:57:12

标签: spring-mvc

我需要在javax.servlet.Filter中自动连接@Service。

public class CORSFilter implements Filter {

    @Autowired
    AccessLogService accessLogService;

    public void setAccessLogService(AccessLogService accessLogService) {
        this.accessLogService = accessLogService;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        // save an access log to the database...

        AccessLogDTO rld = new AccessLogDTO( req );
        accessLogService.addAccessLog( rld );   // <<<--- NPE here! 

        // and do other stuff not related to the question...

    }

}

但我收到NullPointerException错误。

@Service
public class AccessLogServiceImpl implements AccessLogService {
  // ordinary not special service class.
}

1 个答案:

答案 0 :(得分:1)

我们无法直接使用过滤器的依赖注入。虽然您使用的是GenericFilterBean,但您的Servlet过滤器不受spring管理。

请删除@Autowired

AccessLogService accessLogService;

并在doFilter方法中实例化您的服务类。

if(accessLogService==null){
            ServletContext servletContext = request.getServletContext();
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            service = webApplicationContext.getBean(AccessLogService.class);
        }