1. 问题现象与初步定位
最近在Spring Boot项目中集成ShardingJDBC时遇到了一个让人头疼的问题:应用启动时直接抛出NullPointerException,错误信息显示Cannot invoke "Object.toString()" because the return value of "java.util.Map.get(Object)" is null。这个错误发生在数据源初始化阶段,导致整个应用无法启动。
先来看下我当时使用的配置文件(application.yml):
yaml复制spring:
shardingsphere:
datasource:
names: test
test:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
username: root
password: root
sharding:
tables:
t_sequence:
actual-data-nodes: test.t_sequence_$->{0..1}
table-strategy:
inline:
sharding-column: split_no
algorithm-expression: t_sequence_$->{split_no%2}
props:
sql:
show: true
从错误堆栈来看,问题出在setEnvironment方法中的getDataSource环节。这个错误信息很典型,就是尝试调用一个null对象的toString()方法导致的。但为什么会出现这种情况呢?我们需要深入源码一探究竟。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 源码分析与问题根源
通过断点调试,我追踪到了ShardingJDBC初始化数据源的关键代码
