2017-08-11 41 views
3

注释属性的变化应该说我有@Value变化及其对YAML坚持与@Value

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

注解的类的属性,我有这样的属性映射在我的spring配置文件阳明海运:

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

有没有办法来改变包含在属性MYHOST值,并自动反映它的这种变化我configuraton YML文件是永久性的?

例如,“anotherHost”援引本:

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

会导致这个对配置文件:

​​

回答

1

我不知道任何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);