Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'b' defined in file [C:\Users\SZH\IdeaProject\firstcloud\target\classes\szh\demo\test\B.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [szh.demo.test.B]: Constructor threw exception; nested exception is java.lang.NullPointerException --------------------------------------------------
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [szh.demo.test.B]: Constructor threw exception; nested exception is java.lang.NullPointerException ------------------------------------------------------
Caused by: java.lang.NullPointerException at szh.demo.test.B.getC(B.java:21) at szh.demo.test.B.<init>(B.java:18) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ... 55 more
此时的异常栈如下,可以看到在类B里面,第18行,也就是public C cParam =getC();抛出了一空指针异常,这个异常的原因就是在方法getC()里面,c是一个null,那么在这里可能就会有一个疑问了,Spring不是会自动装配有Resource注解的吗?那么此时的c为什么没有被初始化。
@Autowired C c ; { System.out.println("public C cParam =getC()上面一行"); } public C cParam =getC(); { System.out.println("public C cParam =getC()下面一行"); } public C getC(){ return c.getAnewC(); }
}
在此调用测试类,你会发现"public C cParam =getC()上面一行"打印出来之后马上就会出错,这也印证了前面的猜想,这个异常是在初始化B的时候产生的。
@Autowired C c ; { System.out.println("public C cParam =getC()上面一行"); } public C cParam =null; { System.out.println("public C cParam =getC()下面一行"); } public C getC(){ return c.getAnewC(); }