title: Spring boot AbstractRoutingDataSource
body: <p>I'm trying to create a dynamic data source (session based) using AbstractRoutingDataSource but spring boot keeps on calling the determineCurrentLookupKey() function of the AbstractRoutingDataSource  at startup.</p>
  
  <pre><code>@ConfigurationProperties(prefix = "datasource.int")
  @Bean
  public DataSource internal() {
      return DataSourceBuilder.create().build();
  
  }
  
  @ConfigurationProperties(prefix = "datasource.ext")
  @Bean
  public DataSource external() {
      return DataSourceBuilder.create().build();
  }
  
  @Bean(name = "dataSource")
  @Qualifier("dataSource")
  public DynamicRoutingDataSourceResolver dataSource() {
      DynamicRoutingDataSourceResolver resolver = new DynamicRoutingDataSourceResolver();
      DataSource internal = internal();
      DataSource external = external();
      Map&lt;Object, Object&gt; dataSources = new HashMap&lt;&gt;();
      dataSources.put(env.getRequiredProperty("app.param.int"), internal);
      dataSources.put(env.getRequiredProperty("app.param.ext"), external);
      resolver.setDefaultTargetDataSource(internal);
      resolver.setTargetDataSources(dataSources);
      resolver.afterPropertiesSet();
  
      return resolver;
  }
  
  public class DynamicRoutingDataSourceResolver extends  AbstractRoutingDataSource {
  
  @Override
  protected Object determineCurrentLookupKey() {
  
      HttpServletRequest request = ((ServletRequestAttributes)  RequestContextHolder.getRequestAttributes()).getRequest();
      Object o = request.getSession().getAttribute(Constant.DATASOURCE);
      return o;
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>it throws a NullPointerException because the RequestAttributes is null.
  I tried to put @Primary into one of the datasource but the AbstractRoutingDataSource determineCurrentLookupKey()  is not being triggered when I try to execute a query.</p>
  
  <p>I'm using spring data jpa.</p>
  
  <p>see also <a href="https://stackoverflow.com/questions/28610353/spring-boot-with-session-based-data-source/40016380">session based data source</a></p>