Spring Boot-YML配置-合并时删除条目



我的应用程序有一个基本的YML配置,类路径如下:

hello-world:
values:
bar:
name: bar-name
description: bar-description
foo:
name: foo-name
description: foo-description

helloworld包含一个从字符串到POJO的映射,称为values。我想覆盖hello世界中的设置,特别是我想删除一个条目。所以在我运行应用程序的本地目录上,我有这个应用程序。yml:

hello-world:
values:
bar:
name: bar-name
description: bar-description
source: from-the-local-dir

但这不起作用,因为当我的本地配置覆盖现有配置时,映射会合并为一个映射,并保留原始条目"foo"。有没有一种方法可以显式地从spring-yml中的配置映射中删除条目?

PS:通过修改本地文件中的"bar"条目,我可以看到本地文件被选中。这是完整的代码,我添加了一个"源"配置来告诉最后加载了哪个文件:

@Import(PlayGround.Config.class)
@SpringBootApplication
public class PlayGround {
@Autowired
Config config;
@Value("${source}")
String source;
public void start() {
System.out.println(config);
System.out.println(source);
}
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
ConfigurableApplicationContext context = SpringApplication.run(PlayGround.class, args);
PlayGround playGround = context.getBean(PlayGround.class);
playGround.start();
}
@ConfigurationProperties(prefix = "hello-world")
public static final class Config {
Map<String, Information> values = new HashMap<String, Information>();
public Map<String, Information> getValues() {
return values;
}
public void setValues(Map<String, Information> values) {
this.values = values;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("values", values)
.toString();
}
}
public static final class Information {
String name;
String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("description", description)
.toString();
}
}
}

默认情况下,Spring引导从src/main/resource/application.yml获取文件您可以声明config/application.yml,这些配置将覆盖src/main/resources 中的application.yml

你可以试试src/main/resources/application.yml:

hello-world:
bar: 
name: bar-name
description: bar-description
foo: 
name: foo-name
description: foo-description

和config/application.yml

hello-world:
bar: 
name: bar-name
description: bar-description

我认为这会有所帮助因此,当您运行应用程序config/application.yml时,它将覆盖您现有的src/main/resources/application.yml

您可以从config/application.yml中完全删除hello-world但它会抛出一个运行时异常,比如:

Could not resolve placeholder 'hello-world.foo' in value "${hello-world.foo}

要修复它,您可以应用注入值,如:@值("${helloworld.foo:}"(其中在":"之后可以定义默认值

您可以在config/application.yml中保留空字段

hello-world:
bar: 
name: bar-name
description: bar-description
foo: 
name:
description:

默认情况下,如果您不指定foo中的所有值,那么它将为空("(,然后您可以从映射中筛选并删除具有空值的条目。你也可以看看这个类:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/YamlProcessor.ResolutionMethod.html

最新更新