mingli-utils/src/com/mingliqiye/utils/data/ThreadLocalDataHolder.java
minglipro 34dccd1895
All checks were successful
Gitea Actions Build / Build (push) Successful in 51s
feat(utils): 添加 AES 加密解密工具类
- 新增 AesUtils 类,提供 AES/GCM 模式的加密解密方法- 更新 .prettierrc配置,将 useTabs 设置为 true
- 重构 Base64Utils 和 Collection 类的代码结构- 简化 ComponentBean 注解定义
2025-08-17 19:12:08 +08:00

84 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.mingliqiye.utils.data;
/**
* 泛型线程局部变量持有器
* <p>
* 封装了 ThreadLocal 的常用操作,提供更便捷的 API 来管理线程本地变量。
*
* @param <T> 存储的数据类型
* @author MingLiPro
*/
public class ThreadLocalDataHolder<T> {
private final ThreadLocal<T> threadLocal;
/**
* 构造函数,初始化 ThreadLocal 实例
*/
public ThreadLocalDataHolder() {
this.threadLocal = new ThreadLocal<>();
}
/**
* 获取当前线程存储的值
*
* @return 当前线程存储的值如果没有则返回null
*/
public T get() {
return threadLocal.get();
}
/**
* 设置当前线程的值
*
* @param value 要存储的值
*/
public void set(T value) {
threadLocal.set(value);
}
/**
* 移除当前线程存储的值
* <p>
* 防止内存泄漏,使用完毕后应调用此方法清理资源。
*/
public void remove() {
threadLocal.remove();
}
/**
* 获取当前线程存储的值,如果不存在则返回默认值
*
* @param defaultValue 默认值
* @return 当前线程存储的值或默认值
*/
public T getOrDefault(T defaultValue) {
T value = threadLocal.get();
return value != null ? value : defaultValue;
}
/**
* 安全获取值避免NPE
* <p>
* 在某些异常情况下防止抛出异常,直接返回 null。
*
* @return 值或null
*/
public T safeGet() {
try {
return threadLocal.get();
} catch (Exception e) {
return null;
}
}
/**
* 检查当前线程是否有值
*
* @return 是否有值
*/
public boolean isPresent() {
return threadLocal.get() != null;
}
}