1. 程式人生 > 其它 >Bean初始化操作initMethod、@PostConstruct和InitializingBean

Bean初始化操作initMethod、@PostConstruct和InitializingBean

我最新最全的文章都在 南瓜慢說 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

直接在方法上加註解即可:

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

2.3 InitializingBean的afterPropertiesSet方法

需要類實現介面InitializingBean,如下:

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

3 總結

執行後的執行日誌及順序如下:

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


歡迎關注微信公眾號<南瓜慢說>,將持續為你更新...

多讀書,多分享;多寫作,多整理。