1 問題描述
寫了一個組件,內(nèi)部使用 @Component 與 @ConfigurationProperties 注解來讀取 yml 格式的配置文件。因為需要一些初始化操作,所以實現(xiàn)了 CommandLineRunner 接口,并在 run() 方法來進行初始化工作。
@Component
@ConfigurationProperties(prefix = "xxx")
public class DatasourceMapperConfig implements CommandLineRunner {
…
@Override
public void run(String... args) throws Exception {
setDSGroupNames();
setDSNames();
valid();
log.debug("configs -> {}", configs);
}
…
}
當把這個組件打成 jar,加載到 Spring Boot 框架中時,發(fā)現(xiàn) CommandLineRunner 的 run() 并沒有運行,所以初始化的值都是空的:
2 原因分析
因為這個類是被打包在組件中的,所以不會被自動掃描到。即使在 Spring Boot 啟動類中使用 @Import注解導(dǎo)入這個類也無效。因為@Import注解只針對 @Component 注解有效。可惜沒有發(fā)現(xiàn)Spring Boot對自動掃描區(qū)域外的 CommandLineRunner,有什么相關(guān)支持的注解。
3 問題解決
因為是配置類,所以 Spring 框架肯定會執(zhí)行 set 方法,所以把之前的初始化代碼段移放到 set 方法中。
public void setConfigs(List<DatasourceConfig> configs) {
this.configs = configs;
setDSGroupNames();
setDSNames();
valid();
log.debug("configs -> {}", configs);
}