我设置了环境变量
MY_APP_MY_MAP_A1=a
MY_APP_MY_MAP_A2=b
MY_APP_JUSTMAP_A1=a
MY_APP_JUSTMAP_A2=b
通过@ConfigurationProperties
配置我的Spring Boot(2.1.7.RELEASE)应用程序:
@SpringBootApplication
@EnableConfigurationProperties(MyApp.MyProperties.class)
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@Bean
public CommandLineRunner cmd(MyProperties props) {
return args -> {
System.out.println("myMap: " + props.getMyMap());
System.out.println("justmap: " + props.getJustmap());
};
}
@ConfigurationProperties(prefix = "my.app")
@Getter
@Setter
static class MyProperties {
private Map<String, String> myMap;
private Map<String, String> justmap;
}
}
当变量名称包含大写字母(用大写字母表示)时,设置Map<String,String>
无效,否则一切正常:
myMap: null
justmap: {a1=a, a2=b}
有办法吗?
答案 0 :(得分:2)
如果您关注以下环境。传递的变量
MY_APP_MYMAP_A1=a
MY_APP_MYMAP_A2=b
MY_APP_JUSTMAP_A1=a
MY_APP_JUSTMAP_A2=b
下面的代码显示了您的期望
@SpringBootApplication
@EnableConfigurationProperties(TestSpringBootApplication.MyProperties.class)
public class TestSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpringBootApplication.class, args);
}
@Bean
public CommandLineRunner cmd(MyProperties props) {
return args -> {
System.out.println("myMap: " + props.getMyMap());
System.out.println("justmap: " + props.getJustmap());
};
}
@ConfigurationProperties(prefix = "my.app")
static class MyProperties {
private Map<String, String> myMap;
private Map<String, String> justmap;
public Map<String, String> getMyMap() {
return myMap;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
public Map<String, String> getJustmap() {
return justmap;
}
public void setJustmap(Map<String, String> justmap) {
this.justmap = justmap;
}
}
}
输出如下
2019-09-04 16:00:07.336 INFO 21204 --- [ main] c.e.demo.TestSpringBootApplication : Started TestSpringBootApplication in 1.012 seconds (JVM running for 2.219)
myMap: {a1=a, a2=b}
justmap: {a1=a, a2=b}
有关此轻松绑定的规则的更多详细信息,请查看文档here
答案 1 :(得分:0)
详细介绍Shailendra的答案,以下是docs的相关引文:
要将规范形式的属性名称转换为环境变量名称,可以遵循以下规则:
- 用下划线(_)替换点(。)。
- 删除所有破折号(-)。
- 转换为大写。