How to do conditional auto-wiring in Spring?

前端 未结 4 1971
一整个雨季
一整个雨季 2020-11-28 02:59

Has anyone tried to auto-wire different beans into a Spring-managed bean based on a condition? For e.g. if some condition is met, inject class A, else B? I saw in one of the

4条回答
  •  臣服心动
    2020-11-28 03:18

    In your @Configuration class declare a bean to be conditionally created:

    @Bean
    @Conditional(CustomFeatureCondition.class)
    public Stuff stuff() {
        return new Stuff ();
    }
    

    In the place of using just @Autowire it with required = false option:

    @Component
    @Setter(onMethod_ = @Autowired(required = false))
    public class AnotherStuff {
        private Stuff stuff;
        // do stuff here
    }
    

    This way you'll get Stuff bean if it exists in the context and stuff = null if it doesn't.

提交回复
热议问题