Spring fallback bean implementation

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

Scenario

  • There is an interface MyService.
  • I want to provide a default implementation for MyService, name it MyDefaultService.
  • If the component check does not detect any other implementation for MyService, Spring must create an instance MyDefaultServiceas a "backup".
  • If there is a current implementation MyService, say MyCustomService, then the bean should always take precedence over the MyDefaultServiceauto-dependency MyService. In this regard, it MyDefaultServicemust be recessive (as opposed to @Primary).
  • Ideally, there is no need to add additional annotation on MyCustomServiceso that it "redefines" MyDefaultService.
  • Ideally, no explicitly implemented factories or factory methods are required.

Question

Question: how do I need to comment on a class MyDefaultServiceto achieve this?

That I still tried to solve the problem

  • Annotating MyDefaultServiceusing @ConditionalOnMissingBean(MyService.class). It does not work, because it is MyDefaultServicenever used, even if there is no other implementation MyService.
  • , @Primary, . , MyCustomService, , . , @Primary MyDefaultService. ​​.

, - . . , , , -. , UI. . , , , , bean .

,

+4
1

FactoryBean . FactoryBean bean factory beans, MyService, , , bean getObject. , MyDefaultService . factory bean @Primary.

, ():

public class MyServiceFactory implements FactoryBean<MyService> {
    ListableBeanFactory beanFactory;

    public MyService getObject() {
        Map beans = beanFactory.getBeansOfType(MyService.class)
        if (beans.isEmpty())
            return new MyDefaultService(); // plus args, obviously
        else
            return get_some_bean_from_the_map
    }
}

@Primary
@Bean
public MyServiceFactory MyServiceFactory() {
    return new MyServiceFactory();
}

Spring factory bean (.. MyService bean , .

- , , . , , MyService beans.

+4

Source: https://habr.com/ru/post/1569652/


All Articles