美文网首页
SpringBoot @PostConstruct注解

SpringBoot @PostConstruct注解

作者: 夏睡醒了秋 | 来源:发表于2019-10-03 18:34 被阅读0次

依赖注入后将调用被@PostConstruct修饰的方法
像静态方法,或构造方法中调用被注入的对象,则该对象为空
构造时需要使用依赖注入的对象进行初始化时,可以先构造再通过@PostConstruct修饰的方法内进行初始化
1. 代替构造初始化参数

private int count;

@Autowired
private xxxService xxxService;

// 构造
public test(){
  // 此时xxxService为空,依赖注入执行在构造之后
  // this.count = xxxService.selectCount();
}
@PostConstruct
public void init(){
  // 正常初始化 count
  this.count = xxxService.selectCount();
}

2. 使用静态方法时

@Autowired
private xxxService xxxService;

private static Test test;

@PostConstruct
public void init(){
  test = this;
  test.xxxServie = this.xxxService;
}

public static int getCount(){
  return test.xxxService.selectCount();
}

相关文章

网友评论

      本文标题:SpringBoot @PostConstruct注解

      本文链接:https://www.haomeiwen.com/subject/uendpctx.html