Reputation: 419
I have two properties file in a folder in file system. The path of this folder is passed using system properties -D=path/to/properties/folder
ex: java -jar -DpropDir=abc/def app.jar
These are properties files. Please note that both files have common key username,password.
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
Now I want to access all these properties in respective classes. MySqlProperties.java and VerticaProperties.java like this.
@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;
}
}
and similarly 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;
}
}
But as key is same value is overriding for username and password.
How to access mysql.properties in MySqlProperties.java and vertica.properties in VerticaProperties.java classes.
Upvotes: 0
Views: 306
Reputation: 960
You import external properties using @PropertySource
Given the location is shared as
-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 {
....
}
or Given -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 {
....
}
Additionally , you may also use prefix with @ConfigurationProperties along with @PropertySource.
The annotation works best when we have hierarchical properties that all have the same prefix, so we mention the prefix too as a part of the annotation.
Add prefix to keys like mysql.url , vertica.url in respective files
@Component
@PropertySource("${vertica.properties}")
@ConfigurationProperties(prefix="vertica")
public class VerticaProperties {
.....
}
@Component
@PropertySource("${mysql.properties}")
@ConfigurationProperties(prefix="mysql")
public class MySqlProperties {
....
}
Upvotes: 1