在Web开发中线程安全和Properties资源文件配置通过类的加载器获取流

博客介绍了线程安全的一种常用方法,即通过当前线程的类加载器获取properties资源文件的流。

线程安全有好几种方法,这里就写一种目前比较常用的properties资源文件获取流的方式

       通过当前线程的类加载器获取流

public class propertiesTest {

	@org.junit.Test
	public void testName() throws Exception {

		// 创建Properties对象
		Properties properties = new Properties();
		
		// 获取当前线程类的加载器
		ClassLoader con = Thread.currentThread().getContextClassLoader();

		// 线程安全的一种关流方式
		try (

				// 获取当前线程类的加载器获取流的对象    这里相对路径或者使用决定路径
			InputStream resourceAsStream = con.getResourceAsStream("mysql.properties");

	            // 要明白properties处理的是非文本数据  当前类处理的是文本数据,所以我们需要 
                //进行转换流处理
				InputStreamReader iSReader = new InputStreamReader(resourceAsStream);

		) {

			// properties对象properties调用方法
			properties.load(iSReader);
			
			// properties对象properties调用方法:getProperty获取值
			String username = properties.getProperty("user");
			String password = properties.getProperty("pass");

			System.out.println("用户名: " + username + " 用户名密码: " + password);

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值