Python 官方文档:入门教程 => 点击学习
目录注解说明代码示例注解示例错误示例正确示例SpringBoot @PostConstruct虽好,也要慎用1 问题的产生2 案例模拟3 总结注解说明 使用注解: @Pos
@Component
public class PostConstructTest1 {
@Autowired
PostConstructTest2 postConstructTest2;
public PostConstructTest1() {
// postConstructTest2.hello();
}
@PostConstruct
public void init() {
// some init function
}
}
在Bean的初始化操作中,有时候会遇到调用其他Bean的时候报空指针错误。这时候就可以将调用另一个Bean的方法这个操作放到@PostConstruct注解的方法中,将其延迟执行。
@Component
public class PostConstructTest1 {
@Autowired
PostConstructTest2 postConstructTest2;
public PostConstructTest1() {
postConstructTest2.hello();
}
}
@Component
public class PostConstructTest2 {
public void hello() {
System.out.println("hello, i am PostConstructTest2");
}
}
@Component
public class PostConstructTest1 {
@Autowired
PostConstructTest2 postConstructTest2;
public PostConstructTest1() {
postConstructTest2.hello();
}
}
@Component
public class PostConstructTest1 {
@Autowired
PostConstructTest2 postConstructTest2;
public PostConstructTest1() {
// postConstructTest2.hello();
}
@PostConstruct
public void init() {
postConstructTest2.hello();
}
}
做过SpringBoot开发的话,肯定对@PostConstruct比较熟悉。在一个Bean组件中,标记了@PostConstruct的方法会在Bean构造完成后自动执行方法的逻辑。
先说下SpringBoot中Bean的加载过程,简单点说就是SpringBoot会把标记了Bean相关注解(例如@Component、@Service、@Repository等)的类或接口自动初始化全局的单一实例,如果标记了初始化顺序会按照用户标记的顺序,否则按照默认顺序初始化。在初始化的过程中,执行完一个Bean的构造方法后会执行该Bean的@PostConstruct方法(如果有),然后初始化下一个Bean。
那么: 如果@PostConstruct方法内的逻辑处理时间较长,就会增加SpringBoot应用初始化Bean的时间,进而增加应用启动的时间。因为只有在Bean初始化完成后,SpringBoot应用才会打开端口提供服务,所以在此之前,应用不可访问。
为了模拟上面说的情况,在SpringBoot项目中建两个组件类ComponentOne和ComponentTwo。耗时的初始化逻辑放在ComponentOne中,并设置ComponentOne的初始化顺序在ComponentTwo之前。完整代码如下:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ComponentOne {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public ComponentOne() {
this.logger.info("ComponentOne 初始化完成");
}
@PostConstruct
public void init() {
this.logger.info("ComponentOne 模拟耗时逻辑开始");
try {
//这里休眠5秒模拟耗时逻辑
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
logger.info("模拟逻辑耗时失败", e);
}
this.logger.info("ComponentOne 模拟耗时逻辑完成");
}
}
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class ComponentTwo {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public ComponentTwo() {
this.logger.info("ComponentTwo 初始化完成");
}
@PostConstruct
public void init() {
this.logger.info("ComponentTwo 初始化完成后处理");
}
}
启动应用,初始化部分日志如下:
所以,如果应用有一些初始化操作,有以下几点建议:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: 浅谈SpringBoot中的Bean初始化方法 @PostConstruct
本文链接: https://www.lsjlt.com/news/158702.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0