大佬教程收集整理的这篇文章主要介绍了Bean初始化操作initMethod、@PostConstruct和InitializingBean,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我最新最全的文章都在 南瓜慢说 www.pkslow.com ,欢迎大家来喝茶!
很多时间当一个Bean
被创建出来后,我们希望做一些初始化操作,如初始化数据、缓存预热等。有以下三种方法:
initMethod
@PostConstruct
InitializingBean
的afterPropertiesSet
方法先准备一个类用于测试,代码如下:
public class BeanLifecheck implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(BeanLifecheck.class);
@Value("${spring.application.namE}")
private String applicationName;
public BeanLifecheck() {
logger.info("BeanLifecheck: Construct " + applicationName);
}
public void initMethod() {
logger.info("BeanLifecheck: initMethod " + applicationName);
}
@PostConstruct
public void postConstruct() {
logger.info("BeanLifecheck: postConstruct " + applicationName);
}
@PreDestroy
public void preDestroy() {
logger.info("BeanLifecheck: preDestroy " + applicationName);
}
@Override
public void afterPropertiesSet() throws Exception {
logger.info("BeanLifecheck: afterPropertiesSet " + applicationName);
}
}
这个以前是通过xml
配置文件来定义的,现在可以直接定义在@Bean
注解上,如下:
@Bean(initMethod = "initMethod")
public BeanLifecheck beanLifecheck() {
return new BeanLifecheck();
}
直接在方法上加注解即可:
@PostConstruct
public void postConstruct() {
logger.info("BeanLifecheck: postConstruct " + applicationName);
}
需要类实现接口InitializingBean
,如下:
@Override
public void afterPropertiesSet() throws Exception {
logger.info("BeanLifecheck: afterPropertiesSet " + applicationName);
}
运行后的执行日志及顺序如下:
2021-02-06 17:44:52.377: BeanLifecheck: Construct null
2021-02-06 17:44:52.379: BeanLifecheck: postConstruct Springboot-Common
2021-02-06 17:44:52.379: BeanLifecheck: afterPropertiesSet Springboot-Common
2021-02-06 17:44:52.379: BeanLifecheck: initMethod Springboot-Common
2021-02-06 17:45:10.347: BeanLifecheck: preDestroy Springboot-Common
三种方法感觉区别不大,用哪个就看习惯了。
代码请查看:https://github.com/LarryDpk/pkslow-samples
欢迎关注微信公众号<南瓜慢说>,将持续为你更新...
多读书,多分享;多写作,多整理。
以上是大佬教程为你收集整理的Bean初始化操作initMethod、@PostConstruct和InitializingBean全部内容,希望文章能够帮你解决Bean初始化操作initMethod、@PostConstruct和InitializingBean所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。