我在文件系统的一个文件夹中有两个属性文件。使用系统属性传递此文件夹的路径-D= path /to/ properties /folder
例如: java -jar -DpropDir=abc/def app.jar
这些是属性文件。请注意,这两个文件都有公共密钥用户名、密码。
mysql.properties
url=jdbc:mysql://localhost:3306
username=root
password=passvertica.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;
}
}但由于密钥相同,因此用户名和密码的值将被覆盖。
如何在MySqlProperties.java中访问mysql.properties,在VerticaProperties.java类中访问vertica.properties。
发布于 2018-12-26 17:55:10
使用@PropertySource导入外部属性
假设该位置共享为
-Dmysql.properties=file:/path-to-mysql.properties -Dvertica.properties=file:/path-to-vertica.properties
@Component
@PropertySource("${vertica.properties}")
public class VerticaProperties {
.....
}
@Component
@PropertySource("${mysql.properties}")
public class MySqlProperties {
....
}或给定-Dmysql.properties=/path-to-mysql.properties -Dvertica.properties=/path-to-vertica.properties
@Component
@PropertySource("file:${vertica.properties}")
public class VerticaProperties {
.....
}
@Component
@PropertySource("file:${mysql.properties}")
public class MySqlProperties {
....
}此外,您还可以将prefix与@ConfigurationProperties和@PropertySource一起使用。
当我们的层次结构属性都有相同的前缀时,注释效果最好,所以我们也将前缀作为注释的一部分。
在各自的文件中为键添加前缀,如mysql.url、vertica.url
@Component
@PropertySource("${vertica.properties}")
@ConfigurationProperties(prefix="vertica")
public class VerticaProperties {
.....
}
@Component
@PropertySource("${mysql.properties}")
@ConfigurationProperties(prefix="mysql")
public class MySqlProperties {
....
}https://stackoverflow.com/questions/53929978
复制相似问题