可使用如下方式进行注入
public class ControllerFilter implements Filter {
@Autowired
private LogsPutDataBase logsPutDataBase;
@Override
public void init(FilterConfig arg0) throws ServletException {
ServletContext servletContext = arg0.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
logsPutDataBase = (LogsPutDataBase)ctx.getBean("logsPutDataBase");
}
public void destroy () {
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2){
......
return;
}
}
原因:
在Spring中,web应用启动的顺序是:listener->filter->servlet,先初始化listener,然后再来就filter的初始化,再接着才到我们的dispathServlet的初始化,因此,当我们需要在filter里注入一个注解的bean时,就会注入失败,因为filter初始化时,注解的bean还没初始化,没法注入。