简体   繁体   中英

Wiring conditional bean in other bean with contructor injection

Please go through complete question before marking duplicate. Can discuss more in comments

I have following code where ServiceA depends on ServiceB. And serviceB implementation bean will be conditionally initialized

class ServiceA{
   ServiceB serviceB;
   ServiceA(ServiceB serviceB){
      this.serviceB = serviceB;
   }
}


@Configuration
class AppConfig{
   @Conditional("some_condition_based_on_property")
   @Bean
   ServiceB serviceB1(){
     return new ServiceBImpl1();
   }

   @Conditional("some_condition_based_on_property")
   @Bean
   ServiceB serviceB2(){
     return new ServiceBImpl2();
   }

   @Bean
   ServiceA serviceA(){
     //what should go here so that conditional bean is injected in ServiceA
   }

}

I cannot auto-detect ServiceA bean, as I need to inject it in a Map with some key. One option I see is to remove construction injection, and have serviceB bean @autowired in serviceA, which would be last option for me. Any other option?

Edit: I don't want to have if-else during injection, as the beans can be defined at various places. I will be only using @Conditional

Nothing holds you from autowiring the resulting ServiceB right inside the configuration class and reusing the reference it for creating ServiceA :

@Configuration
class AppConfig{
   @Conditional(/* some condition */)
   @Bean
   ServiceB serviceB1(){
     return new ServiceBImpl1();
   }

   @Conditional(/* some condition */)
   @Bean
   ServiceB serviceB2(){
     return new ServiceBImpl2();
   }

   // store a local reference    
   @Autowired
   private dynamicServiceB;

   @Bean
   ServiceA serviceA(){
     return new ServiceA(dynamicServiceB);
   }
}

However, it feels like you're trying to work around some other problem that you didn't describe, especially given you included syntactically incorrect code: @Conditional doesn't accept strings as values. You should not expect that constraining acceptable solutions to those working with a broken bit of code you have will yield much success.

This feels like a scenario for a @Profile .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM