Reputation: 103
I have a property present in application.yml but the value of that property is present in another file. Over here username
is present in file /etc/app/db_username
database:
url: localhost:14482
username: /etc/app/db_username
password: /etc/app/db_password
Is there a way I can have values of username and password from the file automatically instead of me reading the file.
@Value("${database.username}")
String username; //Will give me /etc/app/db_username
@Value("${database.password}")
String password; //Will give me /etc/app/db_password
Upvotes: 4
Views: 4675
Reputation: 5200
You can use @ConfigurationProperties for this:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;
@ConstructorBinding
@ConfigurationProperties("database")
public class DatabaseConfig {
private final String username;
private final String password;
public DatabaseConfig(Path username,
Path password) throws IOException {
this.username = Files.readString(username);
this.password = Files.readString(password);
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
You need to place a @EnableConfigurationProperties(DatabaseConfig.class)
on one of your configuration classes (or the @SpringBootApplication
itself) for this to work.
A complete example on GitHub (with Gradle 7, Java 11 and Spring-Boot 2.5.3): https://github.com/jannis-baratheon/stackoverflow--spring-boot-configurationproperties-file-reading
Upvotes: 1