Spring Boot - 从application.yml注入地图 [英] Spring Boot - inject map from application.yml
问题描述
我有一个 Spring Boot 应用程序,其中包含以下应用程序。 yml
- 基本上来自这里:
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但是,想要注入整个地图,例如:
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
:
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 in问题产生:
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屋!