Spring Boot从YAML(属性)文件中读取数组
Spring Boot从YAML(属性)文件中读取数组
这是我的项目结构
- src - main - java - mypackage - resources - config application.yml
我在application.yml中有这个
document: templates: filetypes: - elem1 - elem2 - elem3 - elem4 hello: test: "hello"
在我的端点中,我有以下内容
@Value("${document.templates.filetypes}") List templatesFileTypes; @Value("${document.hello.test}") String hello;
在任何功能中,我可以访问像System.out.println(hello)
这样的东西,它完全正常工作。
但对于fileTypes而言,它甚至尚未编译,我收到以下错误:
创建名称为\'configurationEndPoint\'的bean时出错:自动连接的依赖项注入失败;嵌套异常是java.lang.IllegalArgumentException: 无法解析占位符“document.templates.filetypes”中的值\"${document.templates.filetypes}\"
我搜索了很多,每一个我能找到的解决方案都是指向正确的application.yml/application.xml文件,但在我的情况下是无效的,因为我可以读取其他测试字符串但不能读取数组;
我尝试过String[]
,也尝试过ArrayList
,但我无法使其工作
另外一种方法是由@Jose Martinez提供的,但实际上不如需要的清晰,因为它将document.templates.filetypes
读取为字符串,然后将其拆分成字符串数组;因此,我在这里提供我的解决方案,
1- 创建一个新类FileTypesProperties
@Configuration @ConfigurationProperties(prefix = "document.templates") public class FileTypesConfig { private ListfileTypes; public List getFileTypes() { return fileTypes; } public void setFileTypes(List fileTypes) { this.fileTypes = fileTypes; } }
2- 创建服务并注入上一个类
@Service public class FileTypeService { private final ListfileTypes; @Autowired public FileTypeService(FileTypesConfig fileTypesConfig){ this.fileTypes = fileTypesConfig.getFileTypes(); } public List getFileTypes(){ return this.fileTypes; } }
3- 在您的端点中简单地自动线和调用上一个服务
@RestController public class ConfigurationEndPoint { @Autowired FileTypeService fileTypeService; @GetMapping("/api/filetypes") @ResponseBody public ResponseEntity> getDocumentTemplatesFileTypes(){ return ResponseEntity.ok(fileTypeService.getFileTypes()); } }
然后您的yaml文件可以是一个真正的数组
document: templates: file-types: - elem1 - elem2 - elem3 - elem4
我认为这比将字符串拆分为较小的字符串数组更清洁,希望这将帮助某人。
一种方法是将元素作为分隔符列表传递。通常我们使用逗号,对于字符串数组来说它可以直接使用。如果要使用List,则需要使用Spring SPEL格式设置分隔符…请参见下面的示例。
document: templates: filetypes:elem1,elem2,elem3
-
@Value("${document.templates.filetypes:}") private String[] array; @Value("#{'${document.templates.filetypes}'.split(',')}") private Listlist; @PostConstruct void testList(){ list.stream().forEach(System.out::println); for (String a : array) { System.out.println(a); } }