How to provide default bean in Spring by condition?

I would like to provide a standard bean custom jar. Only if the user implements a specific class abstract, the default bean injection should be skipped.

The following setup works fine, except for one thing: any classes introduced in a wired class default null! What can I lose?

@Configration
public class AppConfig {
    //use the default service if the user does not provide an own implementation
    @Bean
    @Conditional(MissingServiceBean.class)
    public MyService myService() {
        return new MyService() {};
    }
}


@Component
public abstract class MyService {
    @Autowired
    private SomeOtherService other;

    //default impl of the method, that may be overridden
    public void run() {
        System.out.println(other); //null! Why?
    }
}

public class MissingServiceBean implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getBeanFactory().getBeansOfType(MyService.class).isEmpty();
    }
}

A MyServicebean is created and can also be entered. But the contained classes are null.

If I delete the annotation @Conditioanl, everything works as expected.

+4
source share
2 answers

- @Primary. / . , spring .

@Primary . spring .


spring 4.1+ - List<Intf> supports(...) , supports. a low priority, - . . .

, , . , .

, , , .

+2

:

public abstract class MyService {

    private final SomeOtherService other;

    public MyService(SomeOtherService other) {
       this.other = other;
    }

    //default impl of the method, that may be overridden
    public void run() {
        System.out.println(other);
    }
}

@Configration
public class AppConfig {

    @Autowired
    private SomeOtherService other;

    //use the default service if the user does not provide an own implementation
    @Bean
    @Condition(MissingServiceBean.class)
    public MyService myService() {
        return new MyService(other) {};
    }
}
0

All Articles