【Spring】@PostConstruct注解

当前类的构造 >> @Autowired >> @PostConstruct 执行顺序从左至右以此。 所以当如果某方法依赖于@Autowired或者希望比其晚,那么可以使用@PostConstruct注解。


class A{

@Autowired
private B b;

public A(){
   System.out.println("此时B还未被加载 b = "+b);
}

@PostConstruct
public void init(){
   System.out.println("此时B已经被加载了 b = "+b);
}

}

使用@PostConstruct时多用于初始化的一些操作,不要放入复杂耗时的操作,甚至是死循环。。

注意不要出现下面的代码

@PostConstruct 
    public void init() {
        while(true) {
          ...
        }
	// 或者在这里调用一个不能结束的方法 (比如那个方法内部有while(true))
    }

这样会导致spring启动的时候卡在这个方法中无法继续。。

你可能感兴趣的:(框架)