如何从 ResourceBundle 切换到 Properties(类)?
我有一个应用程序分为 2 个 Java 项目(核心和网络)。核心模块中的 Java 服务必须从位于 Web 模块中的 .properties 文件中读取值。当我使用 ResourceBundle 时,它按预期工作。
我想切换到 Properties 类有几个原因(特别是因为 ResourceBundle 被缓存了,我不想实现 ResourceBundle.Control 没有缓存)。不幸的是,我无法让它工作,特别是因为我找不到要使用的正确相对路径。
我阅读了反编译的 ResourceBundle 类(等),并注意到在某些 ClassLoader 上使用了 getResource()。因此,我没有直接使用 FileInputStream,而是在 ServiceImpl.class 或 ResourceBundle.class 上使用 getResource() 或简单地 getResourceAsStream() 进行测试,但仍然没有成功......
有人知道如何完成这项工作吗?谢谢!
这是我的应用程序核心,服务获取属性值:
app-core
src/main/java
com.my.company.impl.ServiceImpl
public void someRun() {
String myProperty = null;
myProperty = getPropertyRB("foo.bar.key"); // I get what I want
myProperty = getPropertyP("foo.bar.key"); // not here...
}
private String getPropertyRB(String key) {
ResourceBundle bundle = ResourceBundle.getBundle("properties/app-info");
String property = null;
try {
property = bundle.getString(key);
} catch (MissingResourceException mre) {
// ...
}
return property;
}
private String getPropertyP(String key) {
Properties properties = new Properties();
InputStream inputStream = new FileInputStream("properties/app-info.properties"); // Seems like the path isn't the good one
properties.load(inputStream);
// ... didn't include all the try/catch stuff
return properties.getProperty(key);
}
这是属性文件所在的 Web 模块:
app-web
src/main/resources
/properties
app-info.properties