Search code examples
javaspring

Spring multiple beans: Are there other precedence annotations besides `@Primary`?


I will start by explaining my situation. Our applications are divided into a shared project (containing code for all projects) and the specific applications. In the shared project we have an interface together with its implementation

public interface Provider
{
...
}

@Bean
public class ProviderImpl implements Provider
{
...
}

In some applications we need to change the default implementation, so we define another Bean

@Bean
@Primary
public class ApplicationProviderImpl implements Provider
{
...
}

I would like to remove the need to annotate every application-specific implementation with @Primary, so other developers can just provide theire bean implementations as failsafe as possible.

Are there other Annotations beside @Primary which decide which bean implementation is used? Qualifiers could help, but will make it more error-prone in my opinion.


Solution

  • Thanks to the comment from @XtremeBaumer I got a nice solution:

    // in shared project
    @Bean
    @ConditionalOnMissingBean(Provider.class)
    public class ProviderImpl implements Provider
    {
    ...
    }
    

    This basically results in the opposite of @Primary.