Micronaut 二传手注入

问题描述

Micronaut 没有在 setter 方法中注入 @Value。不支持吗?例如,我有

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;
  }

}

解决方法

要使用 setter 注入,必须将 @Inject@Property 结合使用。

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

必须注意一些问题。只需在 Micronaut Docs.

上按 CTRL + F Using the @Property Annotation ,

你的类必须是IoC容器的bean。获取 bean 的最简单方法是使用 @javax.inject.Singleton

注释类

您可以在此处查看示例https://docs.micronaut.io/latest/guide/index.html#valueAnnotation