title: Spring @Async and the AbstractRoutingDataSource
body: <p>I've been using the <a href="http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/" rel="noreferrer">AbstractRoutingDataSource</a> with great success, but have hit upon an issue I can't resolve: when I kick off an asynchronous method using <code>@Async</code>, it loses the local thread's context, and I can't figure out the place to set the database context switch.  Usually I do it an aspect or in a <code>HandlerInterceptor</code>, but <code>@Async</code> doesn't go through any of those usual routes.  Is there an interceptor or something similar I can configure to fire at the beginning and end of the asynch call so that I can set the database context?</p>
  
  <p>Found a similar question on the Spring message boards.  No answer, though: <a href="http://forum.springsource.org/showthread.php?83792-Async-annotated-method-hanging-on-session-scoped-bean" rel="noreferrer">http://forum.springsource.org/showthread.php?83792-Async-annotated-method-hanging-on-session-scoped-bean</a></p>
  
  <p>EDIT: I've debugged the execution flow, and the AbstractRoutingData source <strong>is</strong> in fact getting called in the async thread, but its getting called before the aspect is getting called, so the <code>DataSource</code> is already set in the Hibernate session <strong>before</strong> the <code>ThreadLocal</code> value is getting set.  Looking at the source code for <code>AsyncExecutionInterceptor</code>, which backs <code>@Async</code>, its because the interceptor returns its <code>Order</code> value as <code>HIGHEST_PRECEDENCE</code>, so its getting fired before anything else.</p>
  
  <p><img src="https://i.stack.imgur.com/fMnFF.png" alt="enter image description here"></p>