Spring的注入方式--构造方法--解决需要在构造方法里面去初始化全局变量

本文讨论了Spring框架中构造方法注入的重要性,解析了为何直接使用@Autowired注解在构造方法中会导致Bean创建时的异常,如BeanInstantiationException和NullPointerException。提出了解决方案——采用构造器注入,以确保成员变量的正确加载顺序。此外,还提到了通过在APP启动后初始化全局参数的另一种方法。
摘要由CSDN通过智能技术生成

构造方法注入

public class UserService implements IUserService {

    private IUserDao userDao;

    public UserService(IUserDao userDao) {
        this.userDao = userDao;
    }

}

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

@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
  报错信息说:创建

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值