【问题标题】:How to use @ConfigProperties with a Converter class如何将 @ConfigProperties 与 Converter 类一起使用
【发布时间】:2021-02-13 20:55:51
【问题描述】:

我尝试实现自定义配置类型并且它有效。但是,当我将自定义类型与一组使用 @ConfigProperties 的配置一起使用时,它无法通过名称自动识别属性,而是将属性视为具有嵌套属性的对象。

我怎样才能正确地实现这样的行为? (我是 Quarkus 的新手,如果我在这里做错了,请纠正我)

这是一个转换自定义类型的代码sn-p:

public class Percentage {
    private double percentage;

    public Percentage() {}

    public Percentage(double percentage) {
        this.percentage = percentage;
    }

    public void setPercentage(double percentage) {
        this.percentage = percentage;
    }

    public double getPercentage() {
        return this.percentage;
    }
}

@Priority(300)
public class PercentageConverter implements Converter<Percentage> {

    @Override
    public Percentage convert(String value) {
        int percentIndex = value.indexOf("%");
        return new Percentage(Double.parseDouble(value.substring(0, percentIndex - 1)));
    }

}


/// this works ------

public class Hello {

    @ConfigProperty(name = "custom.vat")
    Percentage vat;

    public Hello () {
    }

   // ..... 

}


/// however, this fails

@ConfigProperties(prefix = "custom")
public class CustomConfig {

    public Percentage vat;

    public Percentage profit;

}

javax.enterprise.inject.spi.DeploymentException: No config value of type [double] exists for: custom.vat.percentage
    at io.quarkus.arc.runtime.ConfigRecorder.validateConfigProperties(ConfigRecorder.java:39)

【问题讨论】:

    标签: quarkus eclipse-microprofile-config


    【解决方案1】:

    不幸的是,我认为这不起作用,因为 Quarkus @ConfigProperties 会像处理子组一样处理这些情况,并尝试将嵌套属性与配置进行映射(而不是使用转换器)。

    如果您认为这应该改变,请随时在 Quarkus GH 中提出问题:https://github.com/quarkusio/quarkus/issues

    或者,您可以使用 SR 配置 @ConfigMapping:https://smallrye.io/docs/smallrye-config/mapping/mapping.html。它涵盖了更多的情况,包括直接转换,并且在未来它可能会取代 Quarkus @ConfigProperties。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多