原因:
在Spring的自动注入中普通的POJO类都可以使用@Autowired进行自动注入,但是除了两类:Filter和Servlet无法使用自动注入属性。(因为这两个归tomcat容器管理)可以用init(集承自HttpServlet后重写init方法)方法中实例化对象。
注意:使用Tomcat war运行才会报这个错,SpringBoot jar运行不影响哦
其实Spring中,web应用启动的顺序是:listener->filter->servlet,先初始化listener,然后再来就filter的初始化,再接着才到我们的dispathServlet的初始化,因此,当我们需要在filter里注入一个注解的bean时,就会注入失败,因为filter初始化时,注解的bean还没初始化,没法注入。
private SLoyApiMessageMapper sLoyApiMessageMapper;
方法1:
@Override
public void init(FilterConfig arg0) throws ServletException {
ServletContext sc = arg0.getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
if(cxt != null && cxt.getBean("SLoyApiMessageMapper") != null && sLoyApiMessageMapper == null){
sLoyApiMessageMapper = (SLoyApiMessageMapper) cxt.getBean("SLoyApiMessageMapper");
}
LOGGER.debug("decode过滤器init");
}
方法2:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
ServletContext sc = req.getSession().getServletContext();
XmlWebApplicationContext cxt =
(XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
if(cxt != null && cxt.getBean("SLoyApiMessageMapper") != null &&
sLoyApiMessageMapper== null)
sLoyApiMessageMapper= (SLoyApiMessageMapper) cxt.getBean("SLoyApiMessageMapper");
}