核心思想
實現InitializingBean介面,重寫afterPropertiesSet方法
範例程式碼
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class Demo implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
log.info("開始休眠5min");
Thread.sleep(1000 * 60 * 5);
log.info("休眠5min結束");
}
}
執行證明
[INFO] 2024-05-22 14:40:24.962 com.xxx.jscaffold.handler.Demo:[12][]- 開始休眠5min
[INFO] 2024-05-22 14:45:24.959 com.xxx.jscaffold.handler.Demo:[14][]- 休眠5min結束
[INFO] 2024-05-22 14:45:26.381 p6spy:[60][]- Consume Time:60 ms 2024-05-22 14:45:26
Execute SQL:SELECT 1
[INFO] 2024-05-22 14:45:26.887 com.jdl.jscaffold.MainApplication:[61][]- Started MainApplication in 308.167 seconds (JVM running for 309.04)
使用場景
可以定義一個sercie來實現InitializingBean介面,用於程式啟動時載入後設資料到記憶體中,如果沒載入完畢,不算springContext成功結束。