上下文应用
上下文的作用在初始时保存公用数据,供任何一层随时调用,目前框架中包涵该功能,我将他提出来记录供以后项目使用;
1.创建RequestContext类,其中定义需要保存的字段和一个线程类
public class RequestContext{ /** *保存当前国际化语言 */ Private String lang; // lang get set /** * 线程类 保存当前线程的上下文类 */ private static ThreadLocal<RequestContext> contextLocal = new ThreadLocal<RequestContext>(); /** * 清理线程遗留的上下文信息 * <功能详细描述> * @see [类、类#方法、类#成员] */ public static void clear() { RequestContext.contextLocal.remove(); } /** * 获取当前线程上下文信息 * <功能详细描述> * @return 当前线程上下文信息 * @see [类、类#方法、类#成员] */ public static RequestContext getContext() { return RequestContext.contextLocal.get(); } /** * 设置当前上下文信息 * <功能详细描述> * @param requestContext 当前上下文信息 * @see [类、类#方法、类#成员] */ public static void putContext(RequestContext requestContext) { RequestContext.contextLocal.set(requestContext); }}
关键是使用ThreadLocal类,
set方法将会用实例名为键传入对象为值的形式保存在线程中.
get方法能够获取在线程中获取实例名对应的值
remove方法清除线程中实例名对应的值