我有一个 Spring Boot具有以下 application.yml
的应用程序 - 基本上取自 here :
info:
build:
artifact: ${project.artifactId}
name: ${project.name}
description: ${project.description}
version: ${project.version}
我可以注入(inject)特定的值,例如
@Value("${info.build.artifact}") String value
不过,我想注入(inject)整个 map ,例如:
@Value("${info}") Map<String, Object> info
这(或类似的)可能吗?显然,我可以直接加载 yaml,但想知道 Spring 是否已经支持。
最佳答案
以下解决方案是@Andy Wilkinson 解决方案的简写,除了它不必使用单独的类或在 @Bean
注释方法上。
application.yml:
input:
name: raja
age: 12
somedata:
abcd: 1
bcbd: 2
cdbd: 3
SomeComponent.java:
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "input")
class SomeComponent {
@Value("${input.name}")
private String name;
@Value("${input.age}")
private Integer age;
private HashMap<String, Integer> somedata;
public HashMap<String, Integer> getSomedata() {
return somedata;
}
public void setSomedata(HashMap<String, Integer> somedata) {
this.somedata = somedata;
}
}
我们可以同时使用 @Value
注释和 @ConfigurationProperties
,没有问题。但是 getter 和 setter 很重要,@EnableConfigurationProperties
必须让 @ConfigurationProperties
才能工作。
我从@Szymon Stepniak 提供的 groovy 解决方案中尝试了这个想法,认为它对某人有用。
关于java - Spring Boot - 从 application.yml 注入(inject) map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917194/