How to autowire by name in Spring with annotations?

前端 未结 1 428
夕颜
夕颜 2020-12-29 04:38

I have several beans of the same class defined:

  @Bean
  public FieldDescriptor fullSpotField() {
     FieldDescriptor ans = new FieldDescriptor(\"full_spot         


        
相关标签:
1条回答
  • 2020-12-29 05:02

    You can use @Qualifier to solve it.

    In your case you can make:

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

    and subsequently you can inject using:

       @Autowired
       @Qualifier("fullSpot")
       public FieldDescriptor fullSpotField;
    
       @Autowired
       @Qualifier("annotationIdSpot")
       public FieldDescriptor annotationIdField;
    
    0 讨论(0)
提交回复
热议问题