【问题标题】:Injecting a custom property from application.properties in quarkus从 quarkus 中的 application.properties 注入自定义属性
【发布时间】:2021-11-22 20:37:30
【问题描述】:

按照指南here 我正在尝试注入我在application.properties 中定义的自定义属性。 prop 定义为sendgrid.apikey=key 然后我的类是;

@ApplicationScoped
public class EmailConfig {

    @Inject
    @ConfigProperty(name = "sendgrid.apikey")
    String API_KEY;

    private SendGrid sendGrid;
    private Request request;

    public EmailConfig() {
        sendGrid = new SendGrid(API_KEY);
        request = new Request();
    }

当我点击构造函数中的第一行时,我希望 API_KEY 是 application.properties 文件中的值,但它是 null。我不知道为什么!顺便说一句,我在有和没有 @Inject 注释的情况下都试过了。

有什么想法吗?

【问题讨论】:

    标签: java properties quarkus


    【解决方案1】:

    你的期望是错误的。有一些技巧可以在不调用构造函数的情况下创建类的实例,但它们通常并不完全可靠,因此 Quarkus 所做的就是您手动执行的操作:创建实例时,它调用构造函数。只有实例存在后才能注入字段。

    你可以做的就是将对象作为参数注入到构造函数中:

    @ApplicationScoped
    public class EmailConfig {
    
        private SendGrid sendGrid;
        private Request request;
    
        @Inject
        public EmailConfig(@ConfigProperty(name = "sendgrid.apikey") String API_KEY) {
            sendGrid = new SendGrid(API_KEY);
            request = new Request();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2022-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多