官方文檔:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-lifecycle
三種方式(如果三種方式同時修飾一個方法,則按照如下順序):
- Methods annotated with @PostConstruct
- afterPropertiesSet() as defined by the InitializingBean callback interface
- A custom configured init() method
測試代碼:
- 通過InitializingBean
@Service
public class EatServiceImpl implements EatService, InitializingBean {
public void afterPropertiesSet() {
System.out.println("afterPropertiesSet");
}
}
- 通過@PostConstruct
@Service
public class SleepServiceImpl implements SleepService {
@PostConstruct
public void postFunction(){
System.out.println("PostConstruct....");
}
}
- 通過自定義方法
public class DrinkServiceImpl implements DrinkService {
public void init(){
System.out.println("drink init...");
}
}
@Configuration
@ComponentScan("com.good.demo3") // 爲了引入AnimalService
public class AppConfig3 {
@Bean(initMethod = "init")
public DrinkServiceImpl eatService(){
return new DrinkServiceImpl();
}
// 這個是爲了下面三個同事修飾
@Bean(initMethod = "init")
public ActionServiceImpl actionService(){
return new ActionServiceImpl();
}
@Bean(initMethod = "afterPropertiesSet")
public ShitServiceImpl shitService(){
return new ShitServiceImpl();
}
}
- 三種同時定義給同一個bean,而且用了不同的方法
public class ActionServiceImpl implements ActionService, InitializingBean {
@PostConstruct
public void postFunction(){
System.out.println("Action PostConstruct....");
}
public void afterPropertiesSet() {
System.out.println("Action afterPropertiesSet");
}
public void init(){
System.out.println("Action init...");
}
}
三種方式同時定義一個bean,而且在一個方法上
public class ShitServiceImpl implements ShitService, InitializingBean {
@PostConstruct
public void afterPropertiesSet() {
System.out.println("Shit afterPropertiesSet...");
}
}
測試方法:
public class TestDemo3 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig3.class);
context.getBean(EatService.class);
context.getBean(DrinkService.class);
context.getBean(SleepService.class);
context.getBean(ActionService.class);
}
}
測試結果:
afterPropertiesSet...
PostConstruct....
drink init...
Action PostConstruct....
Action afterPropertiesSet...
Action init...
Shit afterPropertiesSet...
- 總結下上面三個生命週期回調方法
init-method
、InitializingBean
接口、@PostConstruct
註解- 都是針對單個類的實例化後處理
- 執行時間都是在類實例化完成,且成員變量完成注入之後調用的
- 對於init-method,還可以在Spring配置文件的beans元素下配置默認初始化方法,配置項爲default-init-method
- 若以上三種方式配置的初始化方法都不一樣,則執行順序爲:@PostConstruct註解方法 –> InitializingBean的afterPropertiesSet –> init-method方法 ;若三種方式配置的方法一樣,則方法只執行一次 (參照:Spring官方文檔beans-factory-lifecycle-combined-effect)
- 有初始化回調方法,對應的也有銷燬的回調方法。@PostConstruct註解方法 –> InitializingBean的afterPropertiesSet –> init-method方法 分別對應 @PreDestroy註解方法 –> DisposableBean的destroy –> destroy-method方法
參考:https://blog.csdn.net/liuxigiant/article/details/54296578