考虑在Tomcat中运行的基于Spring的Web应用程序。
我们创建了一个普通的Java EE过滤器,它将ServletRequest
转换为HttpServletRequest
并将其包装到扩展AppHttpServletRequest
的{{1}}。
HttpServletRequestWrapper
然后将public class AppRequestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("Filter start");
AppHttpServletRequest appHttpServletRequest = new AppHttpServletRequest((HttpServletRequest)request);
chain.doFilter(appHttpServletRequest, response);
System.out.println("Filter end");
}
@Override
public void destroy() {}
}
转换为Spring @Autowired
@Component
结果非常令人惊讶:
@Autowired(required = false) private transient AppHttpServletRequest appRequest;
@Autowired(required = false) private transient HttpServletRequest httpRequest;
已自动装配且appRequest
仍为空httpRequest
为空,而appRequest
则自动装配;并且过滤器已经运行... 有人知道为什么这种行为会随机变化?
似乎是在将应用程序部署到Tomcat之后发生的。停止启动应用程序再次修复问题。非常奇怪!