gpt4 book ai didi

java - 在 yaml 上更改并坚持使用 @Value 注释的属性的更改

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:44 25 4
gpt4 key购买 nike

假设我有一个用@Value 注释的类的属性

@RestController
public class MyController{
@Value("${my.host}")
protected String myHost;
...

我将此属性映射到我的 spring 配置 yml 文件中:

...
my.host: 10.0.103.144
my.port: 3003
...

有没有办法更改属性 myHost 中包含的值,并自动将其反射(reflect)在我的配置 yml 文件中,以使此更改持久化?

例如,用“anotherHost”调用它:

private changeHost(String newHost) {
myHost = newHost;
}

在配置文件中会产生这样的结果:

...
my.host: anotherHost
my.port: 3003
...

最佳答案

我不知道有任何 Spring 机制可以自动更新配置文件。

但是,您可以将 Jackson 与 module that supports YAML 一起使用更新您的 YAML 配置文件。它将是这样的:

// Create an ObjectMapper mapper for YAML
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

// Parse the YAML file
ObjectNode root = (ObjectNode) mapper.readTree(new File("/path/to/file.yml"));

// Update the value
root.put("my.host", "anotherHost");

// Write changes to the YAML file
mapper.writer().writeValue(new File("/path/to/file.yml"), root);

关于java - 在 yaml 上更改并坚持使用 @Value 注释的属性的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45637098/

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