java tomcat properties,tomcat 中 java 解析properties(实时变更)

本文探讨了如何在Tomcat环境中实现实时更新Properties文件,通过实例展示了使用getClass().getResourceAsStream()加载资源文件的问题,并提出了解决方案,包括将资源文件放置在非classpath下以解决ClassLoader缓存问题。

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

当前位置:我的异常网» 编程 » tomcat 中 java 解析properties(实时变更)

tomcat 中 java 解析properties(实时变更)

www.myexceptions.net  网友分享于:2015-08-26  浏览:32次

tomcat 中 java 解析properties(实时变化)

有个朋友要用getClass().getResourceAsStream() 提取test.properties

但是在服务器运行过程中 无论怎么更改test.properties

得出的数据还是最初的那个

我后来试了一下 代码如下

package test;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

public class Test {

Properties pp = null;

public Properties getData() throws IOException {

InputStream is = getClass().getResourceAsStream("/test.properties");

// InputStream is = new FileInputStream(

// "D:\\java\\apache-tomcat-5.5.17\\apache-tomcat-5.5.17\\webapps\\testp\\WEB-INF\\classes\\test.properties");

System.out.println(is.hashCode());

pp = new Properties();

pp.load(is);

System.out.println(pp.hashCode());

// Properties pp = System.getProperties();

// Enumeration enu = (Enumeration) pp.propertyNames();

// while(enu.hasMoreElements()){

// String name = enu.nextElement();

// System.out.println(name + "=" +pp.getProperty(name));

// }

// is.close();

is.close();

return pp;

}

public static Properties getProperties() {

try {

return new Test().getData();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

public static void main(String[] args) {

while (true) {

System.out.println(getProperties());

try {

Thread.sleep(1000L);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

上面这个解析的Properties pp 的hashcode 始终不变

而InputStream 的hash 缺一直改变

由此可以推断结论有

getClass().getResourceAsStream() 是ClassLoader 加载Class一样的把test.properties 加载进了内存

但是针对上面的红字我写了MAIN函数做为测试

现在发现如果我更改Properties ,会立刻做出反应

main函数中的代码我的理解如下 每次ClassLoader都在加载ClassPath下的文件,当发现改变就构成Properties 改变

所以我想这是不是tomcat的ClassLoader 的一个bug ??

所以如果想test.properties随时变 用绝对路径 InputStream is = new FileInputStream("绝对路径")

就可以了

主要是因为把资源文件放在classpath下了,而改变了以后,资源文件没有重新编译,因此放入非classpath目录下就可以了

文章评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值