【发布时间】:2018-12-26 09:22:27
【问题描述】:
我在文件系统的一个文件夹中有两个属性文件。 该文件夹的路径是使用系统属性传递的 -D=path/to/properties/folder
例如:java -jar -DpropDir=abc/def app.jar
这些是属性文件。 请注意,这两个文件都有共同的密钥用户名、密码。
mysql.properties
url=jdbc:mysql://localhost:3306
username=root
password=pass
vertica.properties
dburl=jdbc:vertica://123.123.123:4321/abcd
username=abcd
password=pass123
现在我想访问各个类中的所有这些属性。 MySqlProperties.java 和 VerticaProperties.java 像这样。
@Component
public class VerticaProperties {
@Value("${dburl}")
private String dburl;
@Value("${username}")
private String username;
@Value("${password}")
private String password;
public String getDbUrl() {
return dburl;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
和类似的 MySqlProperties.java
@Component
public class MySqlProperties {
@Value("${url}")
private String url;
@Value("${username}")
private String username;
@Value("${password}")
private String password;
public String getDbUrl() {
return url;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
但是由于 key 相同,用户名和密码的值会被覆盖。
如何访问 MySqlProperties.java 中的 mysql.properties 和 VerticaProperties.java 类中的 vertica.properties。
【问题讨论】:
-
如何将这些属性添加到上下文中?使用
PropertySource? -
@talex 我正在使用 PropertyPlaceholderConfigurer bean。
-
我看到的唯一方法是创建您自己的
PropertyPlaceholderConfigurer,它将为键添加前缀,但手动将前缀添加到您的属性会更容易。 -
@talex 我尝试了前缀方法,但它不起作用。 config.setPlaceholderPrefix("${mysql.");收到此错误“无法解析值“${vertica.dburl}”中的占位符“vertica.dburl””
标签: java spring properties