深入Spring Boot:排查@Transactional引起的NullPointerException

简介: 写在前面这个demo来说明怎么排查一个@Transactional引起的NullPointerException。https://github.

写在前面

这个demo来说明怎么排查一个@Transactional引起的NullPointerException

https://github.com/hengyunabc/spring-boot-inside/tree/master/demo-Transactional-NullPointerException

定位 NullPointerException 的代码

Demo是一个简单的spring事务例子,提供了下面一个StudentDao,并用@Transactional来声明事务:

@Component
@Transactional
public class StudentDao {

    @Autowired
    private SqlSession sqlSession;

    public Student selectStudentById(long id) {
        return sqlSession.selectOne("selectStudentById", id);
    }

    public final Student finalSelectStudentById(long id) {
        return sqlSession.selectOne("selectStudentById", id);
    }
}

应用启动后,会依次调用selectStudentByIdfinalSelectStudentById

    @PostConstruct
    public void init() {
        studentDao.selectStudentById(1);
        studentDao.finalSelectStudentById(1);
    }

mvn spring-boot:run 或者把工程导入IDE里启动,抛出来的异常信息是:

Caused by: java.lang.NullPointerException
    at sample.mybatis.dao.StudentDao.finalSelectStudentById(StudentDao.java:27)
    at com.example.demo.transactional.nullpointerexception.DemoNullPointerExceptionApplication.init(DemoNullPointerExceptionApplication.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311)

为什么应用代码里执行selectStudentById没有问题,而执行finalSelectStudentById就抛出NullPointerException?

同一个bean里,明明SqlSession sqlSession已经被注入了,在selectStudentById里它是非null的。为什么finalSelectStudentById函数里是null?

获取实际运行时的类名

当然,我们对比两个函数,可以知道是因为finalSelectStudentById的修饰符是final。但是具体原因是什么呢?

我们先在抛出异常的地方打上断点,调试代码,获取到具体运行时的class是什么:

System.err.println(studentDao.getClass());

打印的结果是:

class sample.mybatis.dao.StudentDao$$EnhancerBySpringCGLIB$$210b005d

可以看出是一个被spring aop处理过的类,但是它的具体字节码内容是什么呢?

dumpclass分析

我们使用dumpclass工具来把jvm里的类dump出来:

https://github.com/hengyunabc/dumpclass

wget http://search.maven.org/remotecontent?filepath=io/github/hengyunabc/dumpclass/0.0.1/dumpclass-0.0.1.jar -O dumpclass.jar

找到java进程pid:

$ jps
5907 DemoNullPointerExceptionApplication

把相关的类都dump下来:

sudo java -jar dumpclass.jar 5907 'sample.mybatis.dao.StudentDao*' /tmp/dumpresult

反汇编分析

用javap或者图形化工具jd-gui来反编绎sample.mybatis.dao.StudentDao$$EnhancerBySpringCGLIB$$210b005d

反编绎后的结果是:

  1. class StudentDao$$EnhancerBySpringCGLIB$$210b005d extends StudentDao
  2. StudentDao$$EnhancerBySpringCGLIB$$210b005d里没有finalSelectStudentById相关的内容

  3. selectStudentById实际调用的是this.CGLIB$CALLBACK_0,即MethodInterceptor tmp4_1,等下我们实际debug,看具体的类型

      public final Student selectStudentById(long paramLong)
      {
        try
        {
          MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
          if (tmp4_1 == null)
          {
            tmp4_1;
            CGLIB$BIND_CALLBACKS(this);
          }
          MethodInterceptor tmp17_14 = this.CGLIB$CALLBACK_0;
          if (tmp17_14 != null)
          {
            Object[] tmp29_26 = new Object[1];
            Long tmp35_32 = new java/lang/Long;
            Long tmp36_35 = tmp35_32;
            tmp36_35;
            tmp36_35.<init>(paramLong);
            tmp29_26[0] = tmp35_32;
            return (Student)tmp17_14.intercept(this, CGLIB$selectStudentById$0$Method, tmp29_26, CGLIB$selectStudentById$0$Proxy);
          }
          return super.selectStudentById(paramLong);
        }
        catch (RuntimeException|Error localRuntimeException)
        {
          throw localRuntimeException;
        }
        catch (Throwable localThrowable)
        {
          throw new UndeclaredThrowableException(localThrowable);
        }
      }

再来实际debug,尽管StudentDao$$EnhancerBySpringCGLIB$$210b005d的代码不能直接看到,但是还是可以单步执行的。

在debug时,可以看到

  1. StudentDao$$EnhancerBySpringCGLIB$$210b005d里的所有field都是null

    cglib-field

  2. this.CGLIB$CALLBACK_0的实际类型是CglibAopProxy$DynamicAdvisedInterceptor,在这个Interceptor里实际保存了原始的target对象

    cglib-target

  3. CglibAopProxy$DynamicAdvisedInterceptor在经过TransactionInterceptor处理之后,最终会用反射调用自己保存的原始target对象

抛出异常的原因

所以整理下整个分析:

  1. 在使用了@Transactional之后,spring aop会生成一个cglib代理类,实际用户代码里@Autowired注入的StudentDao也是这个代理类的实例
  2. cglib生成的代理类StudentDao$$EnhancerBySpringCGLIB$$210b005d继承自StudentDao
  3. StudentDao$$EnhancerBySpringCGLIB$$210b005d里的所有field都是null
  4. StudentDao$$EnhancerBySpringCGLIB$$210b005d在调用selectStudentById,实际上通过CglibAopProxy$DynamicAdvisedInterceptor,最终会用反射调用自己保存的原始target对象
  5. 所以selectStudentById函数的调用没有问题

那么为什么finalSelectStudentById函数里的SqlSession sqlSession会是null,然后抛出NullPointerException

  1. StudentDao$$EnhancerBySpringCGLIB$$210b005d里的所有field都是null
  2. finalSelectStudentById函数的修饰符是final,cglib没有办法重写这个函数
  3. 当执行到finalSelectStudentById里,实际执行的是原始的StudentDao里的代码
  4. 但是对象是StudentDao$$EnhancerBySpringCGLIB$$210b005d的实例,它里面的所有field都是null,所以会抛出NullPointerException

解决问题办法

  1. 最简单的当然是把finalSelectStudentById函数的final修饰符去掉
  2. 还有一种办法,在StudentDao里不要直接使用sqlSession,而通过getSqlSession()函数,这样cglib也会处理getSqlSession(),返回原始的target对象

总结

  • 排查问题多debug,看实际运行时的对象信息
  • 对于cglib生成类的字节码,可以用dumpclass工具来dump,再反编绎分析
相关文章
|
8月前
|
Java 关系型数据库 MySQL
深入解析 @Transactional——Spring 事务管理的核心
本文深入解析了 Spring Boot 中 `@Transactional` 的工作机制、常见陷阱及最佳实践。作为事务管理的核心注解,`@Transactional` 确保数据库操作的原子性,避免数据不一致问题。文章通过示例讲解了其基本用法、默认回滚规则(仅未捕获的运行时异常触发回滚)、因 `try-catch` 或方法访问修饰符不当导致失效的情况,以及数据库引擎对事务的支持要求。最后总结了使用 `@Transactional` 的五大最佳实践,帮助开发者规避常见问题,提升项目稳定性与可靠性。
1328 12
|
11月前
|
XML Java 应用服务中间件
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
2720 17
Spring Boot 两种部署到服务器的方式
|
9月前
|
Java 数据库 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
377 0
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
570 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
781 2
|
缓存 NoSQL Java
Springboot自定义注解+aop实现redis自动清除缓存功能
通过上述步骤,我们不仅实现了一个高度灵活的缓存管理机制,还保证了代码的整洁与可维护性。自定义注解与AOP的结合,让缓存清除逻辑与业务逻辑分离,便于未来的扩展和修改。这种设计模式非常适合需要频繁更新缓存的应用场景,大大提高了开发效率和系统的响应速度。
512 2
|
监控 Java 数据库
Spring事务中的@Transactional注解剖析
通过上述分析,可以看到 `@Transactional`注解在Spring框架中扮演着关键角色,它简化了事务管理的复杂度,让开发者能够更加专注于业务逻辑本身。合理运用并理解其背后的机制,对于构建稳定、高效的Java企业应用至关重要。
462 0
|
数据库连接 数据库 开发者
Spring问题之使用@Transactional注解时需要注意哪些事项
Spring问题之使用@Transactional注解时需要注意哪些事项
166 4
|
Java 开发者 Spring
深入解析 @Transactional:Spring 事务管理的艺术及实战应对策略
深入解析 @Transactional:Spring 事务管理的艺术及实战应对策略
217 2
|
NoSQL Java 应用服务中间件
蓝易云 - Spring redis使用报错Read timed out排查解决
以上都是可能的解决方案,具体的解决方案可能会因具体情况而异。
242 2