Mithunkumar
Mithunkumar

Reputation: 11

handling Multiple implementation of interface

Say I need to rely on several implementations of a Spring bean. I have one AccountService interface and many implementations: DefaultAccountServiceImpl,SpecializedAccountServiceImpl and etc(actual count is 40).

How is this possible (injecting one or the other implementation) in Spring boot?

Which implementation will the following injection use?

Upvotes: 1

Views: 265

Answers (2)

Houssam Badri
Houssam Badri

Reputation: 2509

Use @Qualifier annotation of Spring boot, when autowiring it.

Example:

@Autowired
@Qualifier("defaultAccountServiceImpl")
AccountService defaultAccountServer;

@Autowired
@Qualifier("specializedAccountServiceImpl")
AccountService specializedAccountServiceImpl;

Upvotes: 0

Szellem
Szellem

Reputation: 514

According to this article https://www.logicbig.com/tutorials/spring-framework/spring-core/inject-bean-by-name.html, if there are multiple implementations, a NoUniqueBeanDefinitionException will be thrown. This can be fixed with @Qualifier annotation, where the name of the desired bean should be given.

Upvotes: 1

Related Questions