问题描述:
在最近一次团队review代码时,团队成员发现有将HttpServletRequest 直接通过@Autowired注入的情况,于是大家产生了一个疑问,HttpServletRequest并非Spring中的类,且在没有手动通过@Bean的方式注入,Spring是怎么做到帮开发者完成注入的?
同时,我们知道ioc容器中默认注入的Bean是单例,而每个请求都是独立的,这样不会出问题吗?
为了研究明白为什么,我找了些资料,同时写了个简单的demo研究了下。
Demo类如下:
/**
* @author zhangrenwei
* @date 2022/8/1
* @description replace this
**/
@RestController
public class HttpServletRequestTest {
@Autowired
private HttpServletRequest httpServletRequest;
@GetMapping("/sayHi")
public void sayHi(String name) {
System.out.println(httpServletRequest.getRequestURL().toString());
JSONObject res = new JSONObject();
res.put("requestId", UUID.randomUUID().toString());
res.put("datatime", DateUtils.getDatetime());
// ReturnResult.get(res);
System.out.println("hello: " + name);
}
@PostConstruct
public void after(){
System.out.println(this.httpServletRequest);
}
}

文章详细探讨了Spring如何在没有手动配置的情况下,通过@Autowired自动注入HttpServletRequest。这涉及到Spring的IoC容器、@PostConstruct注解、RequestObjectFactory以及线程安全的实现。关键在于,注入的是HttpServletRequest的一个代理对象,它基于ThreadLocal保证每个请求的独立性和线程安全性。在每个HTTP请求处理过程中,RequestContextFilter初始化并设置ThreadLocal变量,从而实现请求信息的隔离。
2351

被折叠的 条评论
为什么被折叠?



