我最新最全的文章都在 南瓜慢说 www.pkslow.com ,欢送大家来喝茶!

1 简介

很多工夫当一个Bean被创立进去后,咱们心愿做一些初始化操作,如初始化数据、缓存预热等。有以下三种办法:

  • 初始化办法initMethod
  • 注解@PostConstruct
  • InitializingBeanafterPropertiesSet办法

2 三种办法实现

先筹备一个类用于测试,代码如下:

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

2.1 初始化办法initMethod

这个以前是通过xml配置文件来定义的,当初能够间接定义在@Bean注解上,如下:

@Bean(initMethod = "initMethod")public BeanLifeCheck beanLifeCheck() {  return new BeanLifeCheck();}

2.2 注解@PostConstruct

间接在办法上加注解即可:

@PostConstructpublic void postConstruct() {  logger.info("BeanLifeCheck: postConstruct " + applicationName);}

2.3 InitializingBean的afterPropertiesSet办法

须要类实现接口InitializingBean,如下:

@Overridepublic void afterPropertiesSet() throws Exception {  logger.info("BeanLifeCheck: afterPropertiesSet " + applicationName);}

3 总结

运行后的执行日志及程序如下:

2021-02-06 17:44:52.377: BeanLifeCheck: Construct null2021-02-06 17:44:52.379: BeanLifeCheck: postConstruct Springboot-Common2021-02-06 17:44:52.379: BeanLifeCheck: afterPropertiesSet Springboot-Common2021-02-06 17:44:52.379: BeanLifeCheck: initMethod Springboot-Common2021-02-06 17:45:10.347: BeanLifeCheck: preDestroy Springboot-Common

三种办法感觉区别不大,用哪个就看习惯了。

代码请查看:https://github.com/LarryDpk/p...


欢送关注微信公众号<南瓜慢说>,将继续为你更新...

多读书,多分享;多写作,多整顿。