Replace a bean inside the spring container during run-time

It can be easily achieved using a proxy. Create a delegating implementation of your interface and switch object it is delegating to.

@Component("BeanA")
public class MyClass implements MyInterface {
  private MyInterface target;

  public void setTarget(MyInterface target) {
    this.target = target;
  }

  // now delegating implementation of MyInterface methods
  public void method1(..) {
    this.target.method1(..);
  }

  ..
}

Spring introduced the new RefreshScope to replace a bean at runtime. Internally, a proxy is created as described in the answer of mrembisz.

@RefreshScope
@Component
public class MyBean { ... }

Tags:

Java

Spring