1 问题描述
集成了 MyBatis3.x 后,加入 MyBatis 自定义拦截器。抛出 NullPointerException 异常。
完整出错日志如下:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at com.fsti.cc.core.ds.DSApplication.main(DSApplication.java:23) [classes/:na]
Caused by: java.lang.NullPointerException: null
at org.apache.ibatis.session.defaults.DefaultSqlSession.close(DefaultSqlSession.java:263) ~[mybatis-3.5.6.jar:3.5.6]
at org.mybatis.spring.SqlSessionUtils.closeSqlSession(SqlSessionUtils.java:195) ~[mybatis-spring-2.0.6.jar:2.0.6]
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:449) ~[mybatis-spring-2.0.6.jar:2.0.6]
at com.sun.proxy.$Proxy55.selectList(Unknown Source) ~[na:na]
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:224) ~[mybatis-spring-2.0.6.jar:2.0.6]
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:147) ~[mybatis-3.5.6.jar:3.5.6]
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:80) ~[mybatis-3.5.6.jar:3.5.6]
at org.apache.ibatis.binding.MapperProxy$PlainMethodInvoker.invoke(MapperProxy.java:152) ~[mybatis-3.5.6.jar:3.5.6]
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:85) ~[mybatis-3.5.6.jar:3.5.6]
at com.sun.proxy.$Proxy56.selectAll(Unknown Source) ~[na:na]
at com.fsti.cc.core.ds.DSApplication.run(DSApplication.java:28) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
... 5 common frames omitted
自定义的 MyBatis 拦截器采用 Spring 注解 @Bean 注入:
@Configuration
public class MybatisInterceptorConfig {
// @Bean
// public Interceptor getInterceptor(){
// return new UpdateSqlInterceptor();
// }
@Bean
public String addInterceptors(SqlSessionFactory sqlSessionFactory) {
sqlSessionFactory.getConfiguration().addInterceptor(new UpdateSqlInterceptor());
return "MybatisInterceptor";
}
}
这里实际上采用了两种注入方式,试验后发现这两种方式都会抛出同样的异常。
2 原因分析
在自定义 MyBatis 拦截器时,需要实现 plugin 方法,如果使用 IDE 生成的方式就会默认返回 null:
最终导致Executor 对象为 null,所以 MyBatis 在尝试关闭 SqlSession 时,抛出空指针异常。
所以跟我们之前所用的拦截器注入方式没关系。更便捷的方式是直接在拦截器上使用 @Component 注解。形如:
@Component
@Intercepts(
@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class}
))
3 问题解决
参考 Interceptor 类的 plugin 实现方法,使用 Plugin.wrap 包装后再返回回来:
网友评论