[英]Micronaut: How do I map all the properties values in HashMap?
为了学习和一个小规模的项目,我一直在学习 micronaut,但我一直被困在一个问题上。
所以假设我在application.yml文件中有这些数据
output:
-file:
name: PDF
size: 50000
-file:
name: DOCX
size: 35000
所以我的目标是 map 这个确切的数据在 HashMap 中,我可以进一步使用。 我希望我的代码拥有独立于任何条件的所有数据。 如果我添加另一种文件类型,它也应该自动 map 数据。 所以简而言之,最后我想要一个包含 yaml 中所有可用值的Map<name, path> 。 我尝试使用 EachProperty。
https://guides.micronaut.io/micronaut-configuration/guide/index.html#eachProperty但我必须将“名称”作为参数传递。
任何帮助深表感谢。
micronaut @EachProperty
允许从应用程序属性中创建Bean
,因此它将创建具有从嵌套配置键/值派生的属性的 bean ( Singleton
POJO)。
使用@EachProperty
配置时要考虑的一个重要注意事项是它只绑定到顶级配置键,即创建的bean 将以嵌套的top Higher 属性命名,该属性应该是唯一的。
除非更改为以下内容,否则您的配置将不起作用:
output:
# Below config will drive a bean named "pdf", more details below
pdf:
size: 50000
# Below config will drive a bean named "docx"
docx:
size: 35000
请注意,在上面的配置中, name
属性被省略,因为它可以从 bean 配置的名称本身派生:
@EachProperty(value = "output")
public class FileType {
private String name;
private int size;
public FileType(@Parameter("name") String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSize(int size) {
this.size = size;
}
public int getSize() {
return size;
}
@Override
public String toString() {
return "FileType{" +
"name='" + name + '\'' +
", size=" + size +
'}';
}
}
FileType
构造函数将注入配置的 bean 名称(从配置键派生),上述类型将在应用程序运行时生成两个 bean:
FileType{name='pdf', size=50000} FileType{name='docx', size=35000}
由于这些 bean 已经由micronaut核心容器处理,您可以将它们注入任何其他 bean。
否则,如果您希望将 bean 映射到特定的配置格式,例如Map [NAME -> SIZE]
,您可以:
Singleton
bean 作为配置包装器FileType
beanFileType
bean 转换为您的自定义格式下面是一个示例配置包装器:
@Singleton
public class FileTypeConfiguration {
private final Map<String, Integer> fileTypes;
@Inject
public FileTypeConfiguration(List<FileType> fileTypes) {
this.fileTypes = fileTypes.stream()
.collect(
Collectors.toMap(FileType::getName, FileType::getSize)
);
}
public Map<String, Integer> getFileTypes() {
return fileTypes;
}
}
您可以通过FileTypeConfiguration#getFileTypes
访问您的配置( FileTypeConfiguration
必须是@Inject
或通过ApplicationContext
访问)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.