正文
}
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());