Micronaut:如何映射 HashMap 中的所有属性值?

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

所以我的目标是在 HashMap 中映射这个确切的数据,我可以进一步使用它。我希望我的代码拥有独立于任何条件的所有数据。如果我添加另一种文件类型,它也应该自动为此映射数据。 所以简而言之,最后我想要一个 Map ,其中包含 yaml 中所有可用的值。 我尝试使用 EachProperty。

https://guides.micronaut.io/micronaut-configuration/guide/index.html#eachProperty 但我必须将 'name' 作为参数传递。

非常感谢任何帮助。

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:

FileType{name='pdf', size=50000} FileType{name='docx', size=35000}

由于这些 bean 已经由 micronaut 核心容器处理,您可以将它们注入任何其他 bean。

否则,如果您希望将 bean 映射到特定的配置格式,例如 Map [NAME -> SIZE],您可以:

  1. 创建另一个 Singleton bean 作为配置包装器
  2. 注入 FileType 个 bean
  3. 将注入的 FileType bean 映射到您的自定义格式
  4. 使您的配置包装器可以访问此自定义格式

下面是示例配置包装器:

@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 访问)。