Using @Qualifier and @Bean together in Java Config Spring

后端 未结 2 2088
梦毁少年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 19:58

    I think you got the usage of @Qualifier bit wrong.

    If we have more than one bean that qualifies for spring injection, then we use @Qualifer to specify which needs to be used for injection.

    In this case you have two beans Bmw and Mercedes both implementing Drivable interface.

    Presuming I got your intent correct, you want spring to inject Mercedes bean into the Driver object.

    So for that, you need to specify public Driver getDriver(@Qualifier("mercedes") Drivable drivable) in the CarConfig class.

    @Configuration
    @ComponentScan
    class CarConfig {
        @Bean
        public Driver getDriver(@Qualifier("mercedes") Drivable drivable) {
            return new Driver(drivable);
        }
    

    And then you can use AnnotationConfigApplicationContext to load the spring context and subsequently get the Driver bean as below:

        public static void main(String[] args) {
            AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CarConfig.class);
            Driver bean = ctx.getBean(Driver.class);
        }
    }
    

    Just to extend the example, let us say if you want to create a Driver bean for each of Bmw and Mercedes then the sample code would be:

    @Configuration
    @ComponentScan
    class CarConfig {
        @Bean(name="mercedesDriver")
        public Driver getMercedesDriver(@Qualifier("mercedes") Drivable drivable) {
            return new Driver(drivable);
        }
    
        @Bean(name="bmwDriver")
        public Driver getBmwDriver(@Qualifier("bmw") Drivable drivable) {
            return new Driver(drivable);
        }
    
        public static void main(String[] args) {
            AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CarConfig.class);
            System.out.println(Arrays.asList(ctx.getBeanNamesForType(Driver.class)));
            Driver mercedesBean = ctx.getBean("mercedesDriver", Driver.class);
            Driver bmwBean = ctx.getBean("bmwDriver", Driver.class);
        }
    }
    

提交回复
热议问题