本次使用Spring Boot 版本 1.5.9
1 使用@PostConstruct
在任意方法上加入@PostConstruct,例如
@PostConstruct
public void init(){
// do something
}
2 使用Bean注入初始化方法
這種方法需要一個(gè)配置類,也就是加上了@Configuration注解
在返回某個(gè)類的方法上加入@Bean注解進(jìn)行注入,其參數(shù)需帶有initMethod,其值為想要執(zhí)行初始化方法的名稱,配置類例如
@Configuration
public class Config {
@Bean(initMethod = "initMethod")
public InitTest initTest() {
return new InitTest();
}
}
實(shí)際使用的類例如
public class InitTest{
public void initMethod(){
// do something
}
}
3 使用接口InitializingBean
該接口的定義如下
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
通過(guò)實(shí)現(xiàn)這個(gè)接口的afterPropertiesSet方法,來(lái)完成初始化操作,例如
public class InitTestInterface implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
// do something
}
}
Spring Bean初始化執(zhí)行順序
構(gòu)造方法 --> @PostConstruct --> InitializingBean接口 --> @Bean 注入的init-method
在大型系統(tǒng)里千萬(wàn)要注意順序