我们知道,spring中并没有对于单例的bean实现线程安全,所以通常需要开发者自己实现线程安全的操作,下面展示使用ThreadLocal实现单例的bean线程安全的例子:
新建一个springBoot项目,创建一个过滤器,继承OncePerRequestFilter
@Component public class MyFilter extends OncePerRequestFilter { @Autowired private Person person; //使用ThreadLocal对象,把单例的person对象set到ThreadLocal中 public static ThreadLocalauth=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; }
启动项目,分别发送这两个请求,可以验证。