Using @Qualifier and @Bean together in Java Config Spring

后端 未结 2 2057
梦毁少年i
梦毁少年i 2021-01-05 19:31

I have follow code

   interface Drivable{

}

@Component
class Bmw implements Drivable {

}

@Component
class Mercedes implements Drivable {

}

class Driver         


        
2条回答
  •  孤城傲影
    2021-01-05 20:00

    You could define qualifiers for each specific implementations of interface Drivable. Once you did, now you could autowire them into CarConfig class and you have to be create Beans for each Drivers(Mercedz & Benz) along with qualifier names.

    Find below Implementation:

     @Target({ElementType.FIELD, ElementType.PARAMETER})
     @Retention(RetentionPolicy.RUNTIME)
     @Qualifier
     public @interface Bmw {
     }
    
     @Target({ElementType.FIELD, ElementType.PARAMETER})
     @Retention(RetentionPolicy.RUNTIME)
     @Qualifier
     public @interface Mercedes {
     }
    

    Now your Interface Implementations of Driver should be annotated with Qualifiers as below

    @Compoenent
    @Bmw
    public interface Bmw implements Drivable{
    }
    
    @Component
    @Mercedes
    public interface Mercedes implements Drivable{
    }
    

    Your CarConfig class should be as below:

    @Configuration
    public class CarConfig{
    
    @autowire
    @Bmw
    private Drivable bmwDriver;
    
    @autowire
    @Mercedes
    private Drivable mercedesDriver;
    
    
    @Bean
    public Bean getBmwDriver(){
      return new Bmw(bmwDriver);
      }
    
     @Bean
    public Bean getMercedesDriver(){
       return new Mercedes(mercedesDriver);
      }
    
     }
    

    NOTE: if you are creating bean with @Bean, it will be injected byType if there is duplicates then it will injected byName. we no need to mention @Bean(name="bmwDriver") . so you can directly use qualifier("bmwDriver") wherever you need in classes.

提交回复
热议问题