Spring自动装配一个包装好的HttpServletRequest

时间:2014-08-25 19:55:07

标签: java spring spring-mvc

考虑在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

结果非常令人惊讶:

  1. 有时,它按预期工作:@Autowired(required = false) private transient AppHttpServletRequest appRequest; @Autowired(required = false) private transient HttpServletRequest httpRequest; 已自动装配且appRequest仍为空
  2. 有时,它无法正常工作:httpRequest为空,而appRequest则自动装配;并且过滤器已经运行...
  3. 有人知道为什么这种行为会随机变化?

    似乎是在将应用程序部署到Tomcat之后发生的。停止启动应用程序再次修复问题。非常奇怪!

0 个答案:

没有答案