1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Example:

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

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

5 Comments

if i add as you have mentioned, i need to autowire 40 qualifier beans?
Hi Husam, Thanks. i got a instance of a class from the below code. Class<? extends <Interface-name>> sanitizer = EntityServiceImplMap.getInstance().getSortSanitizer(entityId, subEntityId); Now i have userimpl.class value in sanitizer. but when i am accessing the userimpl class methods, i couldnot access it through my sanitizer obj. how can i achieve?
If you need each of your implementation so you have to implement all of them. But you may use Abstract class. I didn't get your above comment sorry.
Thanks, EntityServiceImplMap.getInstance().getSortSanitizer(entityId, subEntityId) is giving the return value as "RolesServiceImpl.class". After getting this value i cannot call the methods from my RolesServiceImpl class through the reference "sanitizer". when i am trying to call sanitizer.newInstance(), I am getting null error for other autowired properties
No problem, check if you may have missed annotating your classes with @Component so that they could be managed by Spring

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.