如何在春季使用注释按名称自动布线?

2022-09-01 07:33:57

我定义了同一类的几个豆子:

  @Bean
  public FieldDescriptor fullSpotField() {
     FieldDescriptor ans = new FieldDescriptor("full_spot", String.class);
     return ans;
  }

  @Bean
  public FieldDescriptor annotationIdField() {
     FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class);
     return ans;
  }

因此,当我自动连接它们时

   @Autowired
   public FieldDescriptor fullSpotField;

   @Autowired
   public FieldDescriptor annotationIdField;

我遇到异常

NoUniqueBeanDefinitionException: No qualifying bean of type [...FieldDescriptor] is defined: expected single matching bean but found ...

如何在XML配置中尽可能按名称自动连接?


答案 1

你可以用它来解决它。@Qualifier

在您的情况下,您可以进行:

 @Bean(name="fullSpot")
 // Not mandatory. If not specified, it takes the method name i.e., "fullSpotField" as qualifier name.
  public FieldDescriptor fullSpotField() {
     FieldDescriptor ans = new FieldDescriptor("full_spot", String.class);
     return ans;
  }

  @Bean("annotationIdSpot")
  // Same as above comment.
  public FieldDescriptor annotationIdField() {
     FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class);
     return ans;
  }

随后,您可以使用以下命令注入:

   @Autowired
   @Qualifier("fullSpot")
   public FieldDescriptor fullSpotField;

   @Autowired
   @Qualifier("annotationIdSpot")
   public FieldDescriptor annotationIdField;

答案 2

这是一个非常简单的“按名称自动布线”的情况,Bean会自行注册到容器中,但在使用按名称自动布线时可能需要构造函数注入。

您可以继续尝试,无论您在哪里自动连接上面指定的2个豆子,

class ExampleClass {
    @Autowired
    public FieldDescriptor fullSpotField;

    @Autowired
    public FieldDescriptor annotationIdField;

    public ExampleClass(FieldDescriptor fullSpotField,FieldDescriptor annotationIdField ){
        super();
        this.fullSpotField = fullSpotField;
        this.annotationIdField = annotationIdField;
    }
}

推荐