micronaut @EachProperty 允许从应用程序属性中驱动 Bean(s) 创建,因此它将创建具有从嵌套配置键 / 派生的属性的 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:
文件类型{name='pdf', size=50000}
文件类型{name='docx', size=35000}
由于这些 bean 已经由 micronaut 核心容器处理,您可以将它们注入任何其他 bean。
否则,如果您希望将 bean 映射到特定的配置格式,例如 Map [NAME -> SIZE],您可以:
- 创建另一个
Singleton bean 作为配置包装器
- 注入
FileType bean
- 将注入的
FileType 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 必须是@Injected 或通过ApplicationContext 访问)。