springannotationsspring-bootautowired

Spring fallback bean implementation


I'm currently trying to configure Spring Boot (using Java Annotations and ComponentScan) for the following scenario:

Scenario

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

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


Solution

  • Traditionally in Spring you could use @Primary annotation to mark a bean, so that it would take precedence over regular beans not annotated with @Primary in case of multiple autowiring candidates are found.

    However, in Spring 6.2 a new annotation was introduced - @Fallback.

    It is essentially the opposite of @Primary. Such bean would be used only in case there are no beans with @Primary annotation AND no regular beans.