【问题标题】:Micronaut not picking up config value through @Value annotationMicronaut 未通过 @Value 注释获取配置值
【发布时间】:2021-08-05 19:03:06
【问题描述】:

我的应用 yaml 是这样的:

my:
  config:
    currentValue: 500

我的代码尝试像这样使用这个值:

@Singleton
public class MyClass {

  @Value("${my.config.current-value}")
  private final int myProperty;

  public MyClass(int myProperty) {
    this.myProperty = myProperty;
  }
}

但它没有启动它,因为当我运行应用程序时出现错误:

{"message":"Internal Server Error: Failed to inject value for parameter [myProperty] of class: com.foo.bar.MyClass Message: No bean of type [java.lang.String] exists. Make sure the bean is not disabled by bean requirements

我错过了什么?

【问题讨论】:

  • 为什么要在字段上既要@Value,又要在构造函数中给字段赋值呢?
  • 我不知道!我做这一切都错了。谢谢!

标签: java dependency-injection javabeans micronaut


【解决方案1】:

如果要使用构造函数注入,则需要将注解放在构造函数参数上。

@Singleton
public class MyClass {
 
  private final int myProperty;

  public MyClass(@Value("${my.config.current-value}") int myProperty) {
    this.myProperty = myProperty;
  }
}

【讨论】:

    【解决方案2】:

    一旦我从构造函数中删除了该属性,它就可以工作了:

    @Singleton
    public class MyClass {
    
      @Value("${my.config.current-value}")
      private int myProperty;
      
    }
    

    【讨论】:

    • "不能同时使用配置值并注入它。" - 那不是真的。您可以注释构造函数参数,也可以注释字段。这两个都将使用将被注入的配置值。
    • 我明白了,谢谢,我会更新答案。我还在学习 Micronaut。
    • 不用担心。我很高兴你明白了。仅供参考……当您直接注入这样的私有字段时,Micronaut 必须使用运行时反射来访问该字段。如果您注释构造函数参数、非私有设置器或非私有字段,则不需要运行时反射。一般来说,需要避免运行时反射。
    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    相关资源
    最近更新 更多