springboot怎么注入yaml中mapstringListstring格式的参数
在Spring Boot中,你可以使用@ConfigurationProperties注解来注入YAML文件中的参数。
首先,创建一个配置类,用于将YAML文件中的参数映射到Java对象中:
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
private Map<String, List<String>> data;
public Map<String, List<String>> getData() {
return data;
}
public void setData(Map<String, List<String>> data) {
this.data = data;
}
}
在YAML文件中,使用myconfig作为前缀来定义参数:
myconfig:
data:
key1:
- value1
- value2
key2:
- value3
- value4
然后,在你的Spring Boot应用程序中,将这个配置类作为一个bean进行注入:
@SpringBootApplication
@EnableConfigurationProperties(MyConfig.class)
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
现在,你可以在其他组件中注入MyConfig对象,并使用其中的数据:
@Component
public class MyComponent {
private final MyConfig config;
public MyComponent(MyConfig config) {
this.config = config;
}
public void printData() {
Map<String, List<String>> data = config.getData();
// 使用data进行操作
}
}
这样,你就可以通过注入MyConfig对象来获取YAML文件中的Map<String, List<String>>格式的参数了
原文地址: https://www.cveoy.top/t/topic/hNQx 著作权归作者所有。请勿转载和采集!