Search code examples
javamicronaut

Micronaut setter injection


Micronaut is not injecting @Value on a setter method. Is it not supported? For example, I have

public class Example {


  @Value("${config.one}") //field injection works
  private String one;

  @Value("${config.two}") //field injection works
  private String two;

  @Value("${config.one}") //setter injection doesn't work
  public void setOne(String one) {
    this.one = one;
  }

  @Value("${config.two}") //setter injection doesn't work
  public void setTwo(String two) {
    this.two = two;
  }

}

Solution

  • To use setter injection, one has to use @Inject in conjunction with @Property.

      @Inject
      public void setOne(@Property(name = "config.one") String one) {
        this.one = one;
      }
    

    There are some gotchas that one must be aware of. Just CTRL + F Using the @Property Annotation on Micronaut Docs.