How to Switch from One DB Instance to Another at Runtime

Sometimes we may need to switch from one db instance from another during runtime. Actually this is very easy if you are using Spring and DataSource API in order to obtain DB connections. Lets look at our solution for such a requirement.

Our solution lays on “proxy pattern“. Spring provides us with ProxyFactoryBean so that we can easily create a proxy bean which is depended on by others instead of real bean and delegates requests to its “target” bean.

Target bean can be directly given to proxy bean or instead it can be accessed over a TargetSource instance. Here we employ a special implementation of TargetSource called as HotSwappableTargetSource. HotSwappableTargetSource bean allows us to swap real target at runtime via its “swap” method. Initially it is configured with an “initialTarget“, however, later it can be replaced with any other suitable bean by just calling swap method given “newTarget” as the input parameter.

Such a requirement may come up with in your project as well. You may want your application to use temporarily another DB instance during maintenance for example. In such cases you will also need to handle other cases such as invalidating currently logged in users’ sessions, object caches etc.