简体   繁体   中英

How to switch/change bean implementation at runtime spring boot?

I have a parent bean and a child bean in the spring configuration class like attached. How can I inject the child bean dynamically into parent bean based on some condition (like feature toggle).

@Configuration
public class FooConfig {

   @Bean
   public void parentBean(@Qualifier("dependantBean") Object bean){
       //use the correct bean at runtime
   }

    @Bean("dependantBean")
    @FeatureToggle(feature = "feature.one", expectedToBeOn = true)
    public Object test1(){
        //some logic and returns a object
       return new Object();
    }

    @Bean("dependantBean")
    @FeatureToggle(feature = "feature.one",expectedToBeOn = false)
    public Object test2(){
       //some logic and returns a object which is different from test1 method
        return new Object();
    }
}

In your example it seems that the decision would be taken when the application starts.

In that case you can handle what bean gets injected with profiles (@Profile).

Side note: Use different names for the method names that create the same bean. The bean name could be the same in this case.

Another alternative could be to create a Map with the 2 dependant beans, and inject the map into the parent bean constructor.

Based on the logic you want you can use any of the two beans in the Map.

In this case use different names for the the two dependant beans.

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