I'm currently trying to configure Spring Boot (using Java Annotations and ComponentScan) for the following scenario:
Scenario
- There's an interface
MyService
. - I want to provide a default implementation for
MyService
, let's call itMyDefaultService
. - If the component scan detects no other implementation for
MyService
, Spring should instantiateMyDefaultService
as a "fallback". - If there is a different implementation of
MyService
present, let's sayMyCustomService
, then that bean should always take precedence overMyDefaultService
when autowiring a dependency toMyService
. In that regard,MyDefaultService
should be recessive (as opposed to@Primary
). - Ideally, there should not need to be an additional annotation on
MyCustomService
to have it "override"MyDefaultService
. - Ideally, no explicitly implemented factories or factory methods should be required.
Question
The question is: how do I need to annotate the MyDefaultService
class in order to achieve this?
What I tried so far to solve the problem
- Annotating
MyDefaultService
with@ConditionalOnMissingBean(MyService.class)
. Didn't work becauseMyDefaultService
is never used, even if there is no other implementation ofMyService
. - There is an annotation called
@Primary
that solves the problem. However, it needs to reside onMyCustomService
, a class that I try to keep free of additional annotations. Essentially, I need the inverse annotation of@Primary
onMyDefaultService
. However, I couldn't find such an annotation.
Concrete use case
I am developing a service layer in one project, and a different project will implement a web UI layer on top of it. The UI project has a dependency to the service layer project. However, for certain functionalities implemented at the service layer, I need to know which user is currently logged in at the web context. So I have to define a service interface for that in the service layer project, such that it can be implemented by the UI project. However, for testing purposes in the service-layer project, I need a default implementation of that interface. Also, in case that the UI project team forgets to implement this interface, the app should not crash, but instead instantiate the fallback bean and issue a warning.
Thanks & kind regards,
Alan
ListableBeanFactory beanFactory
inMyServiceFactory
is null. How to work it out? – Batchelor