Holder模式

本文介绍了一种利用Spring框架自动加载配置文件的方法,并提供了一个简单的线程局部变量管理类实现,便于在Web应用中轻松操作线程相关的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序经常需要用到配置文件,但我们又并不想关心何时读取配置文件,于是写了如下代码,备忘:
/**
* 2007-4-28 下午03:24:37
*/
package kindsoft.auth.internal;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import kindsoft.auth.Configuration;

/**
* the top ContextHolder
* @author <a href="mailto:guileen@gmail.com">桂健雄</a>
* @since 2007-4-28
*/
public class ContextHolder {
private static final Configuration configuration;
static{
ApplicationContext context = new ClassPathXmlApplicationContext("security.xml");
configuration = (Configuration) context.getBean("configuration");
}
/**
* get the configuration
* @return the configuration
*/
public static Configuration getConfiguration() {
return configuration;
}
}


有时我们希望针对每个线程设置一个参数,比如在web程序中,我们使用session来保存信息,但每次必须获得session对象,才可以进行操作,于是有了如下代码,备忘:
/**
* 2007-4-28 下午05:20:05
*/
package kindsoft.auth.internal;

import java.util.HashMap;
import java.util.Map;

/**
* @author <a href="mailto:guileen@gmail.com">桂健雄</a>
* @since 2007-4-28
*/
public class ThreadHolder {
private static ThreadLocal<Map> localMap=new ThreadLocal<Map>(){
@Override
protected Map initialValue() {
return new HashMap();
}
};

@SuppressWarnings("unchecked")
public static void put(String key,Object value){
localMap.get().put(key, value);
}

public static Object get(String key){
return localMap.get().get(key);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值