Spring Boot 优雅配置yml配置文件定义集合、数组和Map
在Spring Boot中,您可以使用YAML配置文件来优雅地定义集合、数组和Map。以下是如何定义和使用它们的示例:
- 集合(List):
my:
servers:
- dev.example.com
- stg.example.com
- prod.example.com
对应的Java类:
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private List<String> servers = new ArrayList<>();
public List<String> getServers() {
return servers;
}
public void setServers(List<String> servers) {
this.servers = servers;
}
}
- 数组:
my:
array:
- 1
- 2
- 3
对应的Java类:
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private int[] array;
public int[] getArray() {
return array;
}
public void setArray(int[] array) {
this.array = array;
}
}
- Map:
my:
mappings:
key1: value1
key2: value2
key3: value3
对应的Java类:
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private Map<String, String> mappings = new HashMap<>();
public Map<String, String> getMappings() {
return mappings;
}
public void setMappings(Map<String, String> mappings) {
this.mappings = mappings;
}
}
确保在Spring Boot应用中启用配置属性支持:
@SpringBootApplication
@EnableConfigurationProperties(MyProperties.class)
public class MyApplication {
// ...
}
然后您可以在需要的地方注入MyProperties
实例:
@Autowired
private MyProperties myProperties;
以上代码展示了如何在Spring Boot应用中定义和使用YAML配置文件中的集合、数组和Map。
评论已关闭