专栏名称: ImportNew
伯乐在线旗下账号,专注Java技术分享,包括Java基础技术、进阶技能、架构设计和Java技术领域动态等。
目录
相关文章推荐
芋道源码  ·  Spring Cloud Gateway ... ·  7 小时前  
芋道源码  ·  面试官:int(1) 和 int(10) ... ·  7 小时前  
芋道源码  ·  入职第一天,看了公司代码,牛马沉默了 ·  昨天  
Java编程精选  ·  Controller层代码这么写,简洁又优雅! ·  2 天前  
Java编程精选  ·  雷军删文,热搜第一! ·  4 天前  
51好读  ›  专栏  ›  ImportNew

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

ImportNew  · 公众号  · Java  · 2018-01-18 15:57

正文

请到「今天看啥」查看全文


}

public final Student finalSelectStudentById(long id) {

return sqlSession.selectOne("selectStudentById", id);

}

}


应用启动后,会依次调用selectStudentById和finalSelectStudentById:


@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());







请到「今天看啥」查看全文