1
votes

Lets assume you have the following Classes extending the Processor interface:

Interface Processor {}

class ProcesorImpl1 implements Processor {}

class ProcesorImpl2 implements Processor {}

Now, Lets assume that you define the following bean in a configuration class in package1:

class ConfigurationClass1 {

    @Bean
    @Qualifier("processor")
    public Processor processor() {
         return new ProcesorImpl1();
    }

}

Next, you define the following bean in a configuration class in package2:

class ConfigurationClass2 {

    @Bean
    @Qualifier("processor")
    public Processor anotherProcessor() {
         return new ProcesorImpl2();
    }

}

The question is how does Spring resolves the following Injection:

@Inject @Qualifier("processor") proc;

What if one of the Beans are annotated with @Primary?

1

1 Answers

1
votes

Qualifier doesn't work with @Bean annotation, but @Primary does and it will define what concrete bean will be injected if you inject a bean by type and there is multiple bean of this type managed by Spring. If you want to inject another non-primary bean, you can mark it with @Qualifier("beanName") annotation to inject it by name. If you define 2 bean with the same names and the same types like this

class ConfigurationClass1 {

    @Bean("processor")
    public Processor processor() {
         return new ProcesorImpl1();
    }

}

class ConfigurationClass2 {

    @Bean("processor")
    public Processor anotherProcessor() {
         return new ProcesorImpl2();
    }

}

Spring will override the first loaded bean within the second and only single will stay in container, because of allowBeanDefinitionOverriding property is set to true by default.