我在文件系统的文件夹中有两个属性文件。 使用系统属性-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;
}
}
但是由于键是相同的,因此用户名和密码的值将被覆盖。
如何访问MySqlProperties.java中的mysql.properties和VerticaProperties.java类中的vertica.properties。
答案 0 :(得分:1)
您使用@PropertySource导入外部属性
鉴于位置共享为
-Dmysql.properties =文件:/path-to-mysql.properties -Dvertica.properties =文件:/path-to-vertica.properties
@Component
@PropertySource("${vertica.properties}")
public class VerticaProperties {
.....
}
@Component
@PropertySource("${mysql.properties}")
public class MySqlProperties {
....
}
或给定 -Dmysql.properties = /路径-mysql.properties -Dvertica.properties = /路径-vertica.properties
@Component
@PropertySource("file:${vertica.properties}")
public class VerticaProperties {
.....
}
@Component
@PropertySource("file:${mysql.properties}")
public class MySqlProperties {
....
}
此外,您还可以在 @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 {
....
}