织梦网站模版官网,网站说建设中,设计制作照片,wordpress 和织梦先看一段代码#xff0c;下面的代码能运行成功吗#xff1f; Autowiredprivate User user;private String school;public UserAccountServiceImpl(){this.school user.getSchool();}
答案是不能。因为Java类会先执行构造方法#xff0c;然后再给注解了Autowired 的user注入…先看一段代码下面的代码能运行成功吗 Autowiredprivate User user;private String school;public UserAccountServiceImpl(){this.school user.getSchool();}
答案是不能。因为Java类会先执行构造方法然后再给注解了Autowired 的user注入值所以在执行构造方法的时候就会报错。 报错信息可能会像下面
Exception in thread main org.springframework.beans.factory.BeanCreationException: Error creating bean with name ... defined in file [....class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [...]: Constructor threw exception; nested exception is java.lang.NullPointerException
报错信息说创建Bean时出错出错原因是实例化bean失败因为bean时构造方法出错在构造方法里抛出了空指针异常。
解决办法是使用构造器注入如下 private User user;private String school;Autowiredpublic UserAccountServiceImpl(User user){this.user user;this.school user.getSchool();} 总结 1、Java变量的初始化顺序为静态变量或静态语句块–实例变量或初始化语句块–构造方法