I have a requirement where i need to configure a Spring based application to work with two databases. We have two databases, one that we use to keep the live data and the other
Spring has exactly what you want - the AbstractRoutingDataSource
. See this blog post on how to use it. In your case, you need to switch the datasource during one request, so you'll need to have 2 transactions, switching the datasource between them by changing the datasource indicator on the ThreadLocal
:
@Transactional(propogation=Propogation.REQUIRES_NEW)
@Aspect
) to fire around the service-layer method calls (using @Around
) to set the ThreadLocal
value before the method call, and to unset it afterwards@Controller
, simply call the Service-layer methods. The Aspect will take care of setting the values to indicate which datasource to use, and the AbstractRoutingDataSource
will use that datasource in the context of each transaction.