SpringBoot【问题 02】@Component + @DS(“xxx“) 多数据源无法切换(问题复现+解决+分析)

1.问题

Java代码:

@Component
@DS("greenplum")
public class GreenPlumComponent {

    @Resource
    private CommonMapper commonMapper;

    private AtomicInteger nextVal;

    @PostConstruct
    public int querySeqNextVal() {
        if (nextVal == null) {
        	// seqName 是通过配置文件传过来的这里为了简洁删除了配置文件代码 
            this.nextVal = new AtomicInteger(commonMapper.querySeqNextValBySeqName("seqName"));
        }
        return nextVal.getAndIncrement();
    }

}

Mapper文件内的SQL:

<select id="querySeqNextValBySeqName" resultType="java.lang.Integer">
	SELECT nextval( #{seqName} )
</select>

运行报错:

Cause: java.sql.SQLSyntaxErrorException: FUNCTION mysql.nextval does not exist; 
bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: 
FUNCTION xa-mysql.nextval does not exist

异常的原因是: 本应该查询greenplum查询的却是mysql,也就是@DS("greenplum")未生效。

2.解决

Java代码去掉 @PostConstruct

@Component
@DS("greenplum")
public class GreenPlumComponent {

    @Resource
    private CommonMapper commonMapper;

    private AtomicInteger nextVal;

    public int querySeqNextVal() {
        if (nextVal == null) {
        	// seqName 是通过配置文件传过来的这里为了简洁删除了配置文件代码 
            this.nextVal = new AtomicInteger(commonMapper.querySeqNextValBySeqName("seqName"));
        }
        return nextVal.getAndIncrement();
    }

}

调用:

	@Autowired
    private GreenPlumComponent greenPlumComponent;
    
    private List<Map> dealData() {
    	// 使用
        int nextVal = greenPlumComponent.querySeqNextVal();
    }

3.分析

可能的问题:

  • 由于 @Component 容器实例化后会调用 @PostConstruct 注解的方法,此时方法的调用并非实例对象调用。
  • @DS 注解利用的是 AOP 非实例对象调用无法触发。

求证后会更新内容,当前仅作记录。

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuanzhengme.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值