How to do conditional auto-wiring in Spring?

前端 未结 4 1958
一整个雨季
一整个雨季 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:21

    I suppose the simpest way:

    @Autowired @Lazy
    protected A a;
    
    @Autowired @Lazy
    protected B b;
    
    void do(){
      if(...) { // any condition
         // use a
      } else {
         // use b
      }
    }
    

    In case you do not declare nessassary bean, Spring throws at runtime NoSuchBeanDefinitionException

提交回复
热议问题