| Version 1 (modified by wuyuanbo, 9 years ago) (diff) |
|---|
1.java类中EnvUtils使用优化
在Env实例依赖servlet的过滤器,其功能也主要是用于处理servlet请求的工具类,在非Controller类或jsp中使用可能会造成错误。
//evn过滤器代码 org.gelivable.web.EnvFilter : 62
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
......
Env env = EnvUtils.getEnv();
envMap.put(env, "");
try {
//下面三个变量只有servlet处理请求时才会被实例化
env.setRequest((HttpServletRequest) request);
env.setResponse((HttpServletResponse) response);
env.setServletContext(servletContext);
request.setAttribute("env", env);
chain.doFilter(request, response);
}
......
}
在聚超值项目中,entity类(service偶尔也会出现)中经常会用env获取service或dao类实例的代码。
public class User {
......
public UserPurchasingInfo getInfo() {
......
info = EnvUtils.getEnv().getBean(GeliDao.class).find(UserPurchasingInfo.class, this.userId);
......
}
......
}
这种代码至少在三种情况下调用会出现错误:
1.在单元测试中
2.不依赖于servlet的定时任务中
3.
public class EnvUtils {
public static Env getEnv() {
return threadLocal.get();
}
public static void removeEnv() {
threadLocal.remove();
}
//通过EnvUtils获取的Env实例是线程单例的
private static final ThreadLocal<Env> threadLocal = new ThreadLocal<Env>() {
@Override
protected Env initialValue() {
return new Env();
}
};
}
![(please configure the [header_logo] section in trac.ini)](http://www1.pconline.com.cn/hr/2009/global/images/logo.gif)