当前位置:   article > 正文

利用ThreadLocal实现全局上下文工具类_通用全局上下文工具类

通用全局上下文工具类
  1. /**
  2. * 全局上下文工具类,用于储存一些东西
  3. */
  4. public class MyContext {
  5. private static final ThreadLocal<Map<Object, Object>> mycontext = new ThreadLocal<Map<Object, Object>>() {
  6. @Override
  7. protected Map<Object, Object> initialValue() {
  8. return new HashMap<Object, Object>();
  9. }
  10. };
  11. /**
  12. * 根据key获取值
  13. * @param key
  14. * @return
  15. */
  16. public static Object getValue(Object key) {
  17. if(mycontext.get() == null) {
  18. return null;
  19. }
  20. return mycontext.get().get(key);
  21. }
  22. /**
  23. * 存储
  24. * @param key
  25. * @param value
  26. * @return
  27. */
  28. public static Object setValue(Object key, Object value) {
  29. Map<Object, Object> cacheMap = mycontext.get();
  30. if(cacheMap == null) {
  31. cacheMap = new HashMap<Object, Object>();
  32. mycontext.set(cacheMap);
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/949012
推荐阅读
相关标签
  

闽ICP备14008679号