升级到Springboot 2 AbstractRoutingDataSource不起作用

时间:2018-06-21 06:47:09

标签: spring-boot

嗨,我使用的是Spring Boot 1.4.0,它工作正常。

当我升级到Spring boot 2.0.0时,出现以下错误。

无法打开JDBC连接进行事务;嵌套的异常是java.lang.IllegalStateException:无法确定查找键[null]的目标DataSource

在org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:305)     在org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:378)     在org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:474)     在org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:289)     在org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)     在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)     在org.springframework.aop.framework.CglibAopProxy $ DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)     在com.vega.ui.service.SecurityServiceImpl $$ EnhancerBySpringCGLIB $$ 5fdaff4b.getTenantIdByUserName()

这是我要实现的代码

公共类TenantContext {     私有静态ThreadLocal currentTenant = new ThreadLocal <>();

public static void setCurrentTenant(Object tenant) {
    System.out.println("tenant : "+tenant);
    currentTenant.set(tenant);
}

public static Object getCurrentTenant() {
    return currentTenant.get();
}

public static void removeTenant() {
    currentTenant.remove();
}

}

公共类TenantRoutingDataSource扩展了AbstractRoutingDataSource {

String tenantId;

private Map<Object, Object> mRountingTargetDataSources;




public void setRountingTargetDataSources(Map<Object, Object> ptargetDataSources) {
    mRountingTargetDataSources = ptargetDataSources;
    this.setTargetDataSources(ptargetDataSources);
}

public Map<Object, Object> getRountingTargetDataSources() {

    return mRountingTargetDataSources;
}

@Override
protected Object determineCurrentLookupKey() {

    if (TenantContext.getCurrentTenant() != null)
        return TenantContext.getCurrentTenant();
    else {
        return tenantId;
    }

}

}

@Bean(name =“ transactionManager”)     @Autowired     公共DataSourceTransactionManager transactionManager(             @Qualifier(“ dbTenantDataSource”)TenantRoutingDataSource dataSource){         logger.info(“ Inside DataSourceTransactionManager”);

    DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
    dataSourceTransactionManager.setRollbackOnCommitFailure(true);
    return dataSourceTransactionManager;
}

0 个答案:

没有答案