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");
相关推荐
lv__pf3 小时前
spring之整合mybatis【TL spring 12】
mysql·spring·mybatis
AI人工智能+电脑小能手4 小时前
大白话说Java设计模式-17-装饰器模式(源码剖析篇)
java·spring·设计模式·装饰器模式·源码分析·io流
counting money9 小时前
Spring AI Alibaba 从入门到实战:构建企业级 AI 应用
java·人工智能·spring
城管不管10 小时前
MySQL 慢查询完整排查
java·服务器·jvm·数据库·mysql·spring·面试
风流 少年19 小时前
Spring AI 2.0:Memory
java·后端·spring
Java成神之路-1 天前
Spring Cloud 微服务契约先行:为什么 Controller 建议要实现 Feign 接口?
spring·spring cloud·微服务
Flittly1 天前
【雕虫大技】Agent 动态 Skill 供应链安全加固(三):输出校验与治理闭环实战
java·spring boot·spring
风流 少年1 天前
Spring AI 2.0:MCP
java·后端·spring
风流 少年1 天前
Spring AI 2.0:Tool
java·python·spring
爱敲键盘的猴子1 天前
Java Spring -- 声明式事务控制
java·spring·事务控制