gpt4 book ai didi

java - Spring Boot - application.yml,从文件中读取值

转载 作者:行者123 更新时间:2023-12-04 17:15:18 26 4
gpt4 key购买 nike

我在 application.yml 中有一个属性,但该属性的值存在于另一个文件中。在这里 username 存在于文件 /etc/app/db_username

database:
url: localhost:14482
username: /etc/app/db_username
password: /etc/app/db_password

有没有一种方法可以自动从文件中获取用户名和密码的值,而不是我读取文件。

@Value("${database.username}")
String username; //Will give me /etc/app/db_username

@Value("${database.password}")
String password; //Will give me /etc/app/db_password

最佳答案

您可以使用 @ConfigurationProperties为此:

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;
}
}

您需要将 @EnableConfigurationProperties(DatabaseConfig.class) 放置在您的配置类之一(或 @SpringBootApplication 本身)上才能使其工作。

GitHub 上的完整示例(使用 Gradle 7、Java 11 和 Spring-Boot 2.5.3):https://github.com/jannis-baratheon/stackoverflow--spring-boot-configurationproperties-file-reading

关于java - Spring Boot - application.yml,从文件中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68809982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com