Mohy Eldeen
Mohy Eldeen

Reputation: 1330

Spring conditional Injection at run time

I was looking at the spring annootation @Conditional to make a runtime conditional wiring of my dependency. I have a service that takes a value in the constructor. I want to create 2 instances of the service with different constructor inputs, then based on a condition at run time, I want to use this bean or that bean. Looks like @Conditional is evaluated on startup time. Is there another way to make my example work on runtime?

Upvotes: 1

Views: 1565

Answers (1)

Adam Kotwasinski
Adam Kotwasinski

Reputation: 4564

You want to create 2 (or more, for that matter) instances and then only use one of them at runtime (what means, it could possibly change over the life of your application).

You can create a holder bean that would delegate the calls to the correct bean.

Let's assume you have:

interface BeanInterface {
  // some common interface
  void f();
};

// original beans a & b
@Bean
public BeanInterface beanA() {
   return new BeanAImpl();
}

@Bean
public BeanInterface beanB() {
   return new BeanBImpl();
}

Then create a wrapper bean:

class Wrapper implements BeanInterface {

   public Wrapper(BeanInterface... beans) { this.delegates = beans };

   private BeanInterface current() { return ... /* depending on your runtime condition */ }

   @Override
   public void f() {
     current().f();
   }
}

And obviously you need to create the wrapper in your configuration

@Bean
public BeanInterface wrapper() {
   return new Wrapper(beanA(), beanB());
}

Upvotes: 1

Related Questions