标签:java
webx 文档中描述:
你不能把一个短期的对象如request、response和request context注入到MyAction这个singleton对象。然而,在Webx中,这样做是可以的!奥秘在于Request Contexts服务对上表所列的这些短期对象作了特殊的处理,使它们可以被注入到singleton对象中。事实上,被注入的只是一个“空壳”,真正的对象是在被访问到的时候才会从线程中取得的。http://openwebx.org/docs/filter.html
例1、
public class MyAction {
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
@Autowired
private ParserRequestContext parser;
}
例2、
public class ManagerHsf {
@Resource
HttpServletRequest request;
@Resource
private HankService hankService;
问题来了, 这个request 的空壳是如何实现,执行request.getParameter(xxx), request.setParameter(xxx)时,到真正的request中取值的。
1、注入的request对象 是HttpServletRequest
2、我们观察request.getParameter(xxx)执行时的,线程堆栈情况,如下,在执行getParameter(xxx) 首先碰到了一个拦截器SpringExtUtil
public class RequestContextBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
private static class RequestProxyTargetFactory implements ProxyTargetFactory {
public Object getObject() {
RequestAttributes requestAttrs = RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttrs).getRequest();
return request;
}
}
....
}
public abstract class RequestContextHolder {
private static final ThreadLocal requestAttributesHolder = new NamedThreadLocal("Request attributes");
private static final ThreadLocal inheritableRequestAttributesHolder =
new NamedInheritableThreadLocal("Request context");
public static RequestAttributes currentRequestAttributes() throws IllegalStateException {
RequestAttributes attributes = getRequestAttributes();
return attributes;
}
public static RequestAttributes getRequestAttributes() {
RequestAttributes attributes = (RequestAttributes) requestAttributesHolder.get();
if (attributes == null) {
attributes = (RequestAttributes) inheritableRequestAttributesHolder.get();
}
return attributes;
......
}
从上面代码中有两个ThreadLocal 对象, 真正的request 对象, 是通过, RequestContextHolder的静态方法,获取得到,当前线程关联的 ”ServletRequestAttributes“对象, 而获取到的。
标签:java
原文地址:http://blog.csdn.net/north_eagle/article/details/44729659