apache / shardingsphere

Empowering Data Intelligence with Distributed SQL for Sharding, Scalability, and Security Across All Databases.
Apache License 2.0
19.96k stars 6.74k forks source link

Cannot subclass final class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource #15086

Closed climy007 closed 2 years ago

climy007 commented 2 years ago

springboot version

2.1.3

sharding-jdbc version

5.0.0

Exception Stack

2022-01-26 14:43:35.276 ERROR 85603 logTag: bizID: errCode: traceID: --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'goodsController': Unsatisfied dependency expressed through field 'goodsMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'goodsMapper' defined in file [//common/mapper/GoodsMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/apache/shardingsphere/spring/boot/ShardingSphereAutoConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) at .web.Application.main(Application.java:58) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'goodsMapper' defined in file [/****/common/mapper/GoodsMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/apache/shardingsphere/spring/boot/ShardingSphereAutoConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1499) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1379) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ... 17 common frames omitted Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/apache/shardingsphere/spring/boot/ShardingSphereAutoConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1305) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1484) ... 28 common frames omitted Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/apache/shardingsphere/spring/boot/ShardingSphereAutoConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ... 41 common frames omitted Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:208) at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:471) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:350) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:299) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:429) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1766) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ... 51 common frames omitted Caused by: java.lang.IllegalArgumentException: Cannot subclass final class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:657) at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33) at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25) at org.springframework.aop.framework.CglibAopProxy$ClassLoaderAwareUndeclaredThrowableStrategy.generate(CglibAopProxy.java:1007) at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:358) at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:582) at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:110) at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:108) at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61) at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34) at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:134) at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:319) at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:569) at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:416) at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:58) at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205) ... 58 common frames omitted

zhaojinchao95 commented 2 years ago

@climy007 Hi, Can you provide a demo or show your configuration?

climy007 commented 2 years ago

you provide a demo or show your conf

shardingsphere:
mode:
type: Standalone
repository:
type: File
props:
sql:
show: true
datasource:
names: db1,db2
db1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:6666/db1?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
username: root
password: 123
db2:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:6666/db2?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
username: root
password: 123
sharding:
default-data-source-name: db1
binding-tables: t_goods
tables:
t_goods:
actual-data-nodes: db$->{1..2}.t_goods
database-strategy:
inline:
sharding-column: id
algorithm-expression: db$->{id % 2 + 1}
key-generator:
column: id
type: SNOWFLAKE
table-strategy:
none:
climy007 commented 2 years ago

@climy007 Hi, Can you provide a demo or show your configuration?

It might be nothing to do with the configuration. After debugging and I found it that the spring will proxy the ShardingsphereDatasource bean to aspect the getConnection method. And then will cast the Exception.

zhaojinchao95 commented 2 years ago
spring:
  shardingsphere:
    props:
      sql-show: true
    datasource:
      ds0:
        username: root
        password: 123456
        url: jdbc:mysql://127.0.0.1:3306/test0
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
      ds1:
        username: root
        password: 123456
        url: jdbc:mysql://127.0.0.1:3306/test1
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
      names: ds0, ds1
    rules:
      sharding:
        sharding-algorithms:
          # 分表算法
          table-inline:
            type: INLINE
            props:
              algorithm-expression: t_user$->{id % 2}
          # 分库算法
          database-inline:
            type: INLINE
            props:
              algorithm-expression: ds$->{sharding_key % 2}

        tables:
          t_user:
            actual-data-nodes: ds$->{0..1}.t_user$->{0..1}
            key-generate-strategy:
              column: id
              key-generator-name: snowflake
            # 分库策略
            database-strategy:
              standard:
                sharding-column: sharding_key
                sharding-algorithm-name: database-inline
            # 分表策略
            table-strategy:
              standard:
                sharding-column: id
                sharding-algorithm-name: table-inline
        key-generators:
          snowflake:
            type: SNOWFLAKE
            props:
              worker-id: 123
    mode:
      type: Standalone
      repository:
        type: File
      overwrite: true

Please refer to the configuration.

climy007 commented 2 years ago
spring:
  shardingsphere:
    props:
      sql-show: true
    datasource:
      ds0:
        username: root
        password: 123456
        url: jdbc:mysql://127.0.0.1:3306/test0
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
      ds1:
        username: root
        password: 123456
        url: jdbc:mysql://127.0.0.1:3306/test1
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
      names: ds0, ds1
    rules:
      sharding:
        sharding-algorithms:
          # 分表算法
          table-inline:
            type: INLINE
            props:
              algorithm-expression: t_user$->{id % 2}
          # 分库算法
          database-inline:
            type: INLINE
            props:
              algorithm-expression: ds$->{sharding_key % 2}

        tables:
          t_user:
            actual-data-nodes: ds$->{0..1}.t_user$->{0..1}
            key-generate-strategy:
              column: id
              key-generator-name: snowflake
            # 分库策略
            database-strategy:
              standard:
                sharding-column: sharding_key
                sharding-algorithm-name: database-inline
            # 分表策略
            table-strategy:
              standard:
                sharding-column: id
                sharding-algorithm-name: table-inline
        key-generators:
          snowflake:
            type: SNOWFLAKE
            props:
              worker-id: 123
    mode:
      type: Standalone
      repository:
        type: File
      overwrite: true

Please refer to the configuration.

I tried. And It seems not the configuration's problem. Still doesn't work.

zhaojinchao95 commented 2 years ago

: Cannot subclass final class org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource

You had better provider a demo project.

terrymanu commented 2 years ago

@climy007 Hi, any update?

linghengqian commented 2 years ago

This may be because you added spring's @Lazy annotation to ShardingSphere's dataSource class, which would conflict with the current version of ShardingSphere if you didn't handle it properly.

lw613315 commented 2 years ago

@climy007 Has this problem been solved? I have the same problem.

lw613315 commented 2 years ago

@zjcnb

io.opentracing.contrib opentracing-spring-cloud-jdbc-starter 0.5.9

The JAR package causes this problem, Please analyze the reasons.

zhaojinchao95 commented 2 years ago

@zjcnb

io.opentracing.contrib opentracing-spring-cloud-jdbc-starter 0.5.9 The JAR package causes this problem, Please analyze the reasons.

I can't analyze it. Because i don't know your project context.

huangxfchn commented 2 years ago

@terrymanu Hi~,Brother Liang. My project also uses open-tracing for jdbc, it will proxy the getConnection() method of javax.sql.DataSource, and spring 2.x uses cglib proxy by default, but ShardingSphereDataSource is a final class. So, if the ShardingSphereDataSource is proxied, this exception will occur. The similar code like this:

@Aspect
public class JdbcAspect {

    @Around("execution(java.sql.Connection *.getConnection(..)) && target(javax.sql.DataSource)")
    public Object getConnection(final ProceedingJoinPoint pjp) throws Throwable {
        return new TracingConnection(conn);
    }

}
huangxfchn commented 2 years ago

@terrymanu Hi~,Brother Liang. My project also uses open-tracing for jdbc, it will proxy the getConnection() method of javax.sql.DataSource, and spring 2.x uses cglib proxy by default, but ShardingSphereDataSource is a final class. So, if the ShardingSphereDataSource is proxied, this exception will occur. The similar code like this:

@Aspect
public class JdbcAspect {

  @Around("execution(java.sql.Connection *.getConnection(..)) && target(javax.sql.DataSource)")
  public Object getConnection(final ProceedingJoinPoint pjp) throws Throwable {
      return new TracingConnection(conn);
  }

}

You can change the proxy of spring to jdk proxy, but it is not recommended. After all, there is a reason why spring boot uses cglib proxy by default. You can refer to the relevant information

In fact, the best way is to disable dynamic proxying for ShardingSphereDataSource. We can change the beanName of ShardingSphereDataSource to shardingSphereDataSource.ORIGINAL and mark it as the original instance, so that Spring AOP will not proxy ShardingSphereDataSource. The relevant code of Spring AOP is as follows:

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#shouldSkip
protected boolean shouldSkip(Class<?> beanClass, String beanName) {
    return AutoProxyUtils.isOriginalInstance(beanName, beanClass);
}

AutoProxyUtils#isOriginalInstance
static boolean isOriginalInstance(String beanName, Class<?> beanClass) {
    if (!StringUtils.hasLength(beanName) || beanName.length() !=
            beanClass.getName().length() + AutowireCapableBeanFactory.ORIGINAL_INSTANCE_SUFFIX.length()) {
        return false;
    }
    return (beanName.startsWith(beanClass.getName()) &&
            beanName.endsWith(AutowireCapableBeanFactory.ORIGINAL_INSTANCE_SUFFIX));
}
  1. Option 1, declare the DataSource defined in ShardingSphereAutoConfiguration.java as @Bean("shardingSphereDataSource.ORIGINAL"), @Bean("dataSource.ORIGINAL")

    public class ShardingSphereAutoConfiguration implements EnvironmentAware {
    @Bean("shardingSphereDataSource.ORIGINAL")
    @Conditional(LocalRulesCondition.class)
    @Autowired(required = false)
    public DataSource shardingSphereDataSource(final ObjectProvider<List<RuleConfiguration>> rules, final ObjectProvider<ModeConfiguration> modeConfig) throws SQLException {
        //……
    }
    
    @Bean("dataSource.ORIGINAL")
    @ConditionalOnMissingBean(DataSource.class)
    public DataSource dataSource(final ModeConfiguration modeConfig) throws SQLException {
        return ShardingSphereDataSourceFactory.createDataSource(schemaName, modeConfig);
    }
    }
  2. Option 2, modify beanName through BeanDefinitionRegistryPostProcessor, the code is as follows:

    
    @Configuration
    public class ShardingSphereRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        String className = ShardingSphereDataSource.class.getName();
        String beanName = "shardingSphereDataSource";
        if(registry.containsBeanDefinition(beanName)){
            BeanDefinition shardingSphereDataSource = registry.getBeanDefinition(beanName);
            registry.removeBeanDefinition(beanName);
            registry.registerBeanDefinition(className + AutowireCapableBeanFactory.ORIGINAL_INSTANCE_SUFFIX , shardingSphereDataSource);
            return;
        }
    }
    
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }

}



Personally, I prefer the official modification of beanName by shardingSphere.
huangxfchn commented 2 years ago

Is‘t necessary to declare ShardingSphereDataSource as a final class?

nealzyf commented 2 years ago

Same issue; here is demo

shardingSphere-jdbc-sample.zip

I also try the below code , but the shardingSphereDataSource via spring aop is null in spring boot 2.3.10. but this code is ok in the spring boot 2.5

@Configuration public class MyDataSourceConfiguration { @Resource private DynamicDataSourceProperties properties;

//           shardingSphereDataSource is null
@Resource(name = "shardingSphereDataSource")
private ShardingSphereDataSource shardingSphereDataSource;

@Bean
public DynamicDataSourceProvider dynamicDataSourceProvider() {
    return new AbstractDataSourceProvider() {

        @Override
        public Map<String, DataSource> loadDataSources() {
            Map<String, DataSource> dataSourceMap = new HashMap<>();
            //           shardingSphereDataSource is null
            dataSourceMap.put("shardingSphere", shardingSphereDataSource);
            return dataSourceMap;
        }
    };
}

@Primary
@Bean
public DataSource dataSource() {
    DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
    dataSource.setPrimary(properties.getPrimary());
    dataSource.setStrict(properties.getStrict());
    dataSource.setStrategy(properties.getStrategy());
    dataSource.setP6spy(properties.getP6spy());
    dataSource.setSeata(properties.getSeata());
    return dataSource;
}

}

linghengqian commented 2 years ago

I also try the below code , but the shardingSphereDataSource via spring aop is null in spring boot 2.3.10. but this code is ok in the spring boot 2.5

nealzyf commented 2 years ago

I also try the below code , but the shardingSphereDataSource via spring aop is null in spring boot 2.3.10. but this code is ok in the spring boot 2.5

Do you have any way to work around?

linghengqian commented 2 years ago

Do you have any way to work around?

@nealzyf Maybe I can't help you. After all, when I first started using ShardingSphere, SpringBoot was released 2.5.1, and it made no sense for me to flip through older versions of the SourceCode. This means that any bugs associated with the stop community supported version of SpringBoot cannot be handled by the Spring community.

climy007 commented 2 years ago

huangxfchn

Thx, this problem is temporary fixed by modifying the ShardingSphereDataSource bean name with the secondary way.

luodadaRyan commented 2 years ago

See if you use Seata. If so, add it to yaml:

seata:
  use-jdk-proxy: true
1205076825 commented 2 days ago

查看您是否使用Seata。如果是,则将其添加到yaml中:

seata:
  use-jdk-proxy: true

感谢,有用