我有两个属性文件:
config-app.properties
config-dev.properties
我试着从第二个女巫那里读到第二个那样的女巫:
String smtpHostName = ResourceBundle.getBundle("config-app").getString("smtp.host.name");
config-app.properties
smtp.host.name =${smtp.host.name.env}
config-dev.properties
smtp.host.name.env =smtp.gmail.com
但我有这样的信息:
Can't find resource for bundle java.util.PropertyResourceBundle
编辑:代码格式.
最佳答案 假设config-app.properties存在于类路径中(在根目录中),这应该可行.您不应该收到错误“无法找到bundle java.util.PropertyResourceBundle的资源”.
但是,通过替换${smtp.host.name.env},您尝试执行的操作将无法与ResourceBundle一起使用.你需要另一个库来做更复杂的事情.
更新
目前尚不清楚你要做什么,但假设你想要开发的配置文件和另一个用于生产的配置文件,你可以尝试做这样的事情:
Properties defaultProperties = new Properties();
defaultProperties.load(new FileInputStream("config-app.properties"));
Properties properties = new Properties(defaultProperties);
if (isDev()) {
properties.load(new FileInputStream("config-dev.properties"));
} else {
properties.load(new FileInputStream("whatever.properties"));
}
properties.getProperty("smtp.host.name");
这将在config-app.properties中具有默认设置,可以根据需要在config-dev.properties或whatever.properties中覆盖.在这种情况下,保持必须相同.
config-app.properties:
smtp.host.name =localhost
config-dev.properties:
smtp.host.name =smtp.gmail.com
最后一点,前面的代码是从文件系统加载文件,如果你在类路径中有它们,请使用类似下面的代码:
defaultProperties.load(Classname.class.getClassLoader().getResourceAsStream("config-app.properties"));