Spring Boot - 从 application.yml 注入地图 [英] Spring Boot - inject map from application.yml
问题描述
我有一个带有以下 application.ymlSpring Boot 的应用程序代码> - 基本上取自 这里:
I have a Spring Boot application with the following application.yml
- taken basically from here:
info:
build:
artifact: ${project.artifactId}
name: ${project.name}
description: ${project.description}
version: ${project.version}
我可以注入特定的值,例如
I can inject particular values, e.g.
@Value("${info.build.artifact}") String value
然而,我想注入整个地图,即像这样:
I would like, however, to inject the whole map, i.e. something like this:
@Value("${info}") Map<String, Object> info
那(或类似的东西)可能吗?很明显,我可以直接加载 yaml,但想知道 Spring 是否已经支持某些东西.
Is that (or something similar) possible? Obviously, I can load yaml directly, but was wondering if there's something already supported by Spring.
推荐答案
您可以使用 @ConfigurationProperties
注入地图:
You can have a map injected using @ConfigurationProperties
:
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
public class MapBindingSample {
public static void main(String[] args) throws Exception {
System.out.println(SpringApplication.run(MapBindingSample.class, args)
.getBean(Test.class).getInfo());
}
@Bean
@ConfigurationProperties
public Test test() {
return new Test();
}
public static class Test {
private Map<String, Object> info = new HashMap<String, Object>();
public Map<String, Object> getInfo() {
return this.info;
}
}
}
使用问题中的 yaml 运行它会产生:
Running this with the yaml in the question produces:
{build={artifact=${project.artifactId}, version=${project.version}, name=${project.name}, description=${project.description}}}
有多种选项可用于设置前缀、控制缺失属性的处理方式等.请参阅 javadoc 了解更多信息.
There are various options for setting a prefix, controlling how missing properties are handled, etc. See the javadoc for more information.
这篇关于Spring Boot - 从 application.yml 注入地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!