先看一段代码,下面的代码能运行成功吗?

    @Autowired
    private 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;

    @Autowired
    public UserAccountServiceImpl(User user){
        this.user = user;
        this.school = user.getSchool();
    }

总结:
1、Java变量的初始化顺序为:静态变量或静态语句块–>实例变量或初始化语句块–>构造方法

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐