threadLocal的运用

复制代码
 RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //使用哪一个取决于springmvc在保存request信息时具体用的子类,他们通常无父子单独实现、
        //如果有父子可以继承第一个持有的httpServletRequest
        HttpServletRequest request = ((ServletWebRequest) requestAttributes).getRequest();
        //ServletRequestAttributes它是spring的具体保存的实例实现,通过名字和实现目的 接口是属性目的获取请求servlet
//        ServletRequestAttributes它是最上乘的类其他实现者以继承它保存的request并初始出自己的,并提供自己的get和set
         HttpServletRequest request1 = ((ServletRequestAttributes) requestAttributes).getRequest();
        HttpServletRequest request3 = ((StandardServletAsyncWebRequest) requestAttributes).getRequest();

        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        System.out.println(requestURI+method);

抽象类 RequestContextHolder提供静态方法,获取全局的threadlocal对象,对象中存一个请求属性对象接口,该接口有多个实现类,提供顶层接口以外的附加功能,但在springMVC中把请求保存在当前线程的只会有一个实例实现,其他实例通过继承这个实例同样持有到属性接口实例持有的HttpServletRequest对象,通过 RequestContextHolder类为每一个请求到的线程中都加上一个缓存map,值的接口实例持有请求属性,由于是静态的属性所以所有线程可以使用设置自己的值,获取线程之间存值有交集

复制代码
 private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes");
    private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context");
相关推荐
listening77713 分钟前
HarmonyOS 6.1 元服务深度优化:从“秒开”到“常驻”的极致体验
java·开发语言·spring
空中湖5 小时前
Spring AI Agent 编排:ReAct 模式 + 多 Agent 协作实战
人工智能·spring·react.js
yio_yin1 天前
Spring事务管理(数据一致性)
数据库·sql·spring
dear_bi_MyOnly1 天前
【SpringBoot配置文件】
java·spring boot·后端·学习·spring·java-ee·学习方法
our_times1 天前
2026年Java开发者破局指南:Spring AI 2.0 与 Agent 开发实战
java·人工智能·spring
wear工程师1 天前
@Transactional 标了却没开事务?先看这次调用有没有经过代理
java·spring
爱学习的小可爱卢1 天前
SpringCloud——微服务实战:OpenFeign与Nacos服务调用详解
spring·spring cloud·微服务
静水楼台x1 天前
spring security
java·数据库·spring
咖啡八杯2 天前
GoF设计模式——解释器模式
java·后端·spring·设计模式
糖果店的幽灵2 天前
【DeepAgents 从入门到精通】Context Management 上下文管理
java·人工智能·后端·spring·中间件·langgraph·deepagents