Sobes.tech
Junior — Middle

Is it possible to dynamically override or replace a Bean during application runtime?

sobes.tech AI

Answer from AI

In the standard Spring Framework, it is not possible to dynamically override or replace a Bean at runtime directly, as the Spring context is created at startup and is immutable in terms of bean definitions.

However, there are several approaches to achieve a similar effect:

  • Using @Primary and profiles to select the desired implementation at startup.
  • Using BeanFactory or ApplicationContext to obtain a bean, then changing the logic inside the bean itself (for example, through the strategy pattern).
  • Using ConfigurableApplicationContext and the refresh() method, but this is a complex and rarely used approach.
  • Injecting proxy objects that can change behavior during runtime.

Example with a proxy for dynamic behavior replacement:

public interface Service {
    void execute();
}

public class ServiceImpl1 implements Service {
    public void execute() { System.out.println("Impl1"); }
}

public class ServiceImpl2 implements Service {
    public void execute() { System.out.println("Impl2"); }
}

public class ServiceProxy implements Service {
    private Service delegate;

    public ServiceProxy(Service initial) {
        this.delegate = initial;
    }

    public void setDelegate(Service delegate) {
        this.delegate = delegate;
    }

    public void execute() {
        delegate.execute();
    }
}

Thus, the ServiceProxy bean remains unchanged, but its internal implementation can change dynamically.

Is it possible to dynamically override or replace a… - sobes.tech