定义上下文
public class ThreadContext<T> {
private static final ThreadLocal<ThreadContext<?>> LOCAL = new ThreadLocal<>();
private ThreadContext(){}
public static <T> ThreadContext<T> init(){
ThreadContext<T> context = new ThreadContext<>();
LOCAL.set(context);
return context;
}
public static <T> ThreadContext<T> get(){
return (ThreadContext<T>) LOCAL.get();
}
public static void fill(UserInfo userInfo){
ThreadContext<UserInfo> context = ThreadContext.get();
context.setAddress(userInfo.getAddress());
context.setUserId(userInfo.getUserId());
context.setUserName(context.getUserName());
}
public static ThreadContext<?> set(ThreadContext<?> context){
ThreadContext<?> backup = get();
LOCAL.set(context);
return backup;
}
public static void clear(){
LOCAL.remove();
}
private String userName;
private Long userId;
private String address;
public Long getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
定义用户信息
public class UserInfo {
private String userName;
private Long userId;
private String address;
public Long getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
定义注解用于切面
@Inherited
@Retention(
RetentionPolicy.RUNTIME
)
@Target({ElementType.METHOD})
public @interface ThreadScene {
String userName();
String address();
long userId();
}
定义切面
@Aspect
@Component
public class TreadSceneAspect {
@Around("@annotation(scene)")
public Object around(ProceedingJoinPoint joinPoint,ThreadScene scene) throws Throwable{
ThreadContext<Object> originContext = ThreadContext.get();
ThreadContext<Object> context = originContext;
if(context == null){
context = ThreadContext.init();
}
String userName = context.getUserName();
Long userId = context.getUserId();
String address =context.getAddress();
try{
context.setUserName(scene.userName());
context.setUserId(scene.userId());
context.setAddress(scene.address());
return joinPoint.proceed();
}finally {
if(originContext == null){
ThreadContext.clear();
}else {
context.setAddress(address);
context.setUserId(userId);
context.setUserName(userName);
}
}
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/280438.html