Search code examples
javadependency-injectionjavabeansmicronaut

Micronaut not picking up config value through @Value annotation


My application yaml is like so:

my:
  config:
    currentValue: 500

And my code tries to use this value like so:

@Singleton
public class MyClass {

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

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

But it isn't picking it up, because when I run the application I get an error:

{"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

What am I missing?


Solution

  • If you want to use constructor injection, you need to put the annotation onto the constructor parameter.

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