@rkenmi - Spring - Injecting more than one bean of the same type

Spring - Injecting more than one bean of the same type


Spring - Injecting more than one bean of the same type


Back to Top

Updated on January 13, 2020

Problem

By default, Spring will autowire beans by type. When a bean is created that depends on other beans, it will check for the existence of the required dependencies by types. Creating another bean of the same type will result in a very common exception: NoUniqueBeanDefinitionException.

Solution

Use the @Qualifier annotation on either method parameters, constructor arguments or the field itself. By using @Qualifier, you can specify which exact bean to use.

    @Autowired
    public void prepare(@Qualifier("imdb") MovieCatalog movieCatalogA, @Qualifier("metacritic") MovieCatalog movieCatalogB, CustomerPreferenceDao customerPreferenceDao) {
        ...
    }

Another solution would be to use the @Primary on a Spring Component, so that by default, Spring will choose that bean when it encounters multiple beans of the same type and it does not know which bean to choose from. This could lead to unrefined code, but it can also get the job done.


Article Tags:
SpringSpring BeansJava