首页 > 其他 > 详细

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

时间:2020-06-16 21:28:15      阅读:389      评论:0      收藏:0      [点我收藏+]

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());
);
}

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

原文:https://www.cnblogs.com/hbuuid/p/13144611.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!