@PostConstruct和static静态块初始化的区别

static blocks are invoked when the class is being initialized, after it is loaded. The dependencies of your component haven't been initialized yet. That is why you get a NullPointerException (Your dependencies are null) .

Move your code to a method annotated with @PostConstruct. This will ensure that your code will run when all the dependencies of your component are initialized
译文:static模块会被引入,当class加载后。你的component组件的依赖还没有初始化。这就是为什么你的代码块会报空指针异常。(你的依赖都是null)

1,@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,

为此,可以使用@PostConstruct注解一个方法来完成初始化,

@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

2,执行优先级高于非静态的初始化块,它会在类初始化(类加载的初始化阶段)的时候执行一次,执行完成便销毁,它仅能初始化类变量,即static修饰的数据成员。

初始化失败:

static {
strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
   System.out.println("初始化完成" + strategyMap.size());
}

初始化成功:

@PostConstruct
void init() {
strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
System.out.println("初始化完成" + strategyMap.size());
);
}
原文地址:https://www.cnblogs.com/hbuuid/p/13144611.html