栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

Spring的bean用ThreadLocal保证线程安全

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring的bean用ThreadLocal保证线程安全

我们知道,spring中并没有对于单例的bean实现线程安全,所以通常需要开发者自己实现线程安全的操作,下面展示使用ThreadLocal实现单例的bean线程安全的例子:

新建一个springBoot项目,创建一个过滤器,继承OncePerRequestFilter 

@Component
public class MyFilter extends OncePerRequestFilter {
    @Autowired
    private Person person;

    //使用ThreadLocal对象,把单例的person对象set到ThreadLocal中
    public static ThreadLocal auth=new ThreadLocal();

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        auth.set(person);

        doFilter(request,response,filterChain);
    }
}

Person类如下:

@Component
public class Person {
    public int age;
}

为了简单起见,我们person类只有一个属性,

写两个controler:

@GetMapping("/h1")
    public int hhh(){
        Person person = MyFilter.auth.get();
        person.age=111;
        return person.age;
    }

    @GetMapping("/h2")
    public int hhh1(){
        Person person = MyFilter.auth.get();
        person.age=112;
        return person.age;
    }

启动项目,分别发送这两个请求,可以验证。

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1036489.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号