Learn more about NullPointerException caused by @ Transactional in Spring Boot,

Source: Internet
Author: User

Learn more about NullPointerException caused by @ Transactional in Spring Boot,

Preface

This demo describes how to troubleshoot NullPointerException caused by @ Transactional.

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

Code for locating NullPointerException

Demo is a simple spring transaction example. It provides the following StudentDao and uses @ Transactional to declare the transaction:

@Component@Transactionalpublic 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); }}

After the application is started, it will call selectStudentById and finalSelectStudentById in sequence:

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

Use mvn spring-boot: run or import the project to the IDE for startup. The exception information is as follows:

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)

Why is there no problem in executing selectStudentById in the application code, and executing finalSelectStudentById throws NullPointerException?

In the same bean, it is clear that SqlSession sqlSession has been injected. In selectStudentById, It is not null. Why is the finalSelectStudentById function null?

Obtain the actual class name

Of course, we can compare the two functions because the modifier of finalSelectStudentById is final. But what is the specific reason?

First, we need to break the breakpoint where an exception is thrown, debug the code, and obtain the specific runtime class:

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

The printed result is:

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

It can be seen that it is a class processed by spring aop, but what is its specific bytecode content?

Dumpclass Analysis

We use the dumpclass tool to dump the classes in jvm:

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

Find the java Process pid:

$ jps5907 DemoNullPointerExceptionApplication

Dump all related classes:

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

Disassembly Analysis

Use javap or jd-gui to decomcode sample. mybatis. dao. StudentDao $ EnhancerBySpringCGLIB $ 210b005d.

The result after the anti-encoding is:

class StudentDao$$EnhancerBySpringCGLIB$$210b005d extends StudentDao

StudentDao$$EnhancerBySpringCGLIB$$210b005dNO content related to finalSelectStudentById

SelectStudentById actually calls this. CGLIB $ CALLBACK_0, that is, MethodInterceptor tmp4_1. Let's wait for the actual debug to see the specific type.

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 again. Although the Code of StudentDao $ EnhancerBySpringCGLIB $ 210b005d cannot be seen directly, it can still be executed in one step.

When debugging, you can see

1. StudentDao $ EnhancerBySpringCGLIB $ all fields in 210b005d are null

 

2. The actual type of this. CGLIB $ CALLBACK_0 is CglibAopProxy $ DynamicAdvisedInterceptor. The original target object is actually saved in this Interceptor.

 

3. CglibAopProxy $ DynamicAdvisedInterceptor after TransactionInterceptor processing, the original target object saved by itself will be called through reflection.

Cause of exception thrown

So sort out the entire analysis:

1. After @ Transactional is used, spring aop will generate a cglib proxy class. In actual user code, the StudentDao injected by @ Autowired is also an instance of this proxy class.

2. The agent class StudentDao generated by cglib $ EnhancerBySpringCGLIB $ 210b005d inherits from StudentDao

3. StudentDao $ EnhancerBySpringCGLIB $ all fields in 210b005d are null

4. StudentDao $ EnhancerBySpringCGLIB $ 210b005d call selectStudentById. Actually, through CglibAopProxy $ DynamicAdvisedInterceptor, the original target object saved by yourself will be called through reflection.

5. Therefore, the selectStudentById function is called.

So why does the SqlSession sqlSession in the finalSelectStudentById function be null and then the NullPointerException is thrown?

1. StudentDao $ EnhancerBySpringCGLIB $ all fields in 210b005d are null

2. the modifier of the finalSelectStudentById function is final, and cglib cannot rewrite this function.

3. When the code is executed in finalSelectStudentById, the code in the original StudentDao is actually executed.
4. But the object is a StudentDao $ EnhancerBySpringCGLIB $ 210b005d instance. All fields in it are null, so NullPointerException will be thrown.

Solution

1. the simplest of course is to remove the final modifier of the finalSelectStudentById function.

2. There is another way to avoid using sqlSession directly in StudentDao, but through the getSqlSession () function, cglib will also process getSqlSession () and return the original target object

Summary

1. troubleshoot multiple debugging issues and check the object information during actual running.

2. For the bytecode of the cglib generation class, you can use dumpclass to dump and re-compile the encoding analysis.

Summary

The above is an in-depth study of NullPointerException caused by @ Transactional in Spring Boot. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.