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

构造方法注入

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
  报错信息说:创建Bean时出错,出错原因是实例化bean失败,因为bean时构造方法出错,在构造方法里抛出了空指针异常。

  解决办法是,使用构造器注入,如下:

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

可以看出,使用构造器注入的方法,可以明确成员变量的加载顺序

PS:Java变量的初始化顺序为:静态变量或静态语句块–>实例变量或初始化语句块–>构造方法–>@Autowired

通过这种方法你可以实现调用某个Service的方法来初始化一些全局参数,或者做缓存预加载等。

还有另外一种方法也可以实现,那就是

@Component
@Order(10)
public class Init implements ApplicationRunner {
    public void init() {
        // do something
    }
}

这种方式是在APP启动之后去初始化,也可以实现初始化全局参数

扫描二维码关注公众号,回复: 3255557 查看本文章

猜你喜欢

转载自blog.csdn.net/tianhouquan/article/details/82659918