threadLocal的概念这里不做表述,主要说下如何使用
例如: 我们在service层需要用到request,除了注入/传参数的形式外,还可以使用threadLocal,当然,threadLocal还可以用在其他情况,非常方便
首先定义要使用的类
public class ThreadLocalContext {
private static ThreadLocal<HttpServletRequest> threadRequest = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> threadResponse = new ThreadLocal<HttpServletResponse>();
public static void setRequest(HttpServletRequest request) {
threadRequest.set(request);
}
public static HttpServletRequest getRequest() {
HttpServletRequest request = threadRequest.get();
return request;
}
public static void removeRequest() {
threadRequest.remove();
}
public static void setResponse(HttpServletResponse response) {
threadResponse.set(response);
}
public static HttpServletResponse getResponse() {
HttpServletResponse response = threadResponse.get();
return response;
}
public static void removeResponse() {
threadResponse.remove();
}
}
里面变量写成静态,这里是使用request的,如上,主要包括get/set/remove方法,这里要记住每次使用完之后,要remove掉,不然容易产生内存泄露问题,使用try-catch的方式:
try{
//do something
ThreadLocalContext.setRequest(request);
ThreadLocalContext.setResponse(response);
}catch(Exception e){
e.printStackTrace();
}finally{
ThreadLocalContext.removeRequest();
ThreadLocalContext.removeResponse();
}