目錄
1. 初始化階段執行順序
1.1 Bean的構造方法(構造函數)
1.2?@PostConstruct?注解方法
1.3?InitializingBean?的?afterPropertiesSet()
1.4?@Bean(initMethod = "自定義方法")
2. 上下文就緒后的擴展點
2.1?ApplicationContext?事件監聽器
2.2?ApplicationRunner?與?CommandLineRunner
3. 完整執行順序總結
4. 控制執行順序的方法
5. 示例代碼驗證
????????在Spring Boot應用中,容器初始化及組件執行的順序遵循特定的生命周期。以下是常見的初始化組件及其執行順序的詳細說明,幫助您合理控制代碼邏輯的加載順序。
1. 初始化階段執行順序
以下是Spring Boot應用啟動時,各初始化方法的執行順序(從上到下依次執行):
1.1 Bean的構造方法(構造函數)
- 觸發時機:Bean實例化時。
- 說明:Bean被容器創建時,構造函數首先被調用。
@Component
public class MyBean {public MyBean() {System.out.println("構造方法執行");}
}
1.2?@PostConstruct
?注解方法
- 觸發時機:Bean依賴注入完成后。
- 說明:在Bean屬性賦值(如
@Autowired
注入)之后執行。
@Component
public class MyBean {@PostConstructpublic void init() {System.out.println("@PostConstruct方法執行");}
}
1.3?InitializingBean
?的?afterPropertiesSet()
- 觸發時機:與
@PostConstruct
類似,但由Spring原生接口提供。 - 說明:在Bean屬性設置完成后執行,優先于自定義的
init-method
。
@Component
public class MyBean implements InitializingBean {@Overridepublic void afterPropertiesSet() {System.out.println("InitializingBean的afterPropertiesSet執行");}
}
1.4?@Bean(initMethod = "自定義方法")
- 觸發時機:在
@PostConstruct
和InitializingBean
之后執行。 - 說明:通過
@Bean
注解顯式指定的初始化方法。
@Configuration
public class AppConfig {@Bean(initMethod = "customInit")public AnotherBean anotherBean() {return new AnotherBean();}
}public class AnotherBean {public void customInit() {System.out.println("@Bean的initMethod執行");}
}
2. 上下文就緒后的擴展點
當所有Bean初始化完成后,應用進入上下文就緒階段:
2.1?ApplicationContext
?事件監聽器
ContextRefreshedEvent
?監聽器:當ApplicationContext
初始化或刷新完成后觸發。@Component public class MyContextListener {@EventListener(ContextRefreshedEvent.class)public void onContextRefreshed() {System.out.println("ContextRefreshedEvent事件觸發");} }
2.2?ApplicationRunner
?與?CommandLineRunner
- 觸發時機:在上下文就緒后、應用啟動完成前執行。
- 執行順序:通過
@Order
或實現Ordered
接口控制多個Runner的順序。@Component @Order(1) public class MyAppRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) {System.out.println("ApplicationRunner執行");} }@Component @Order(2) public class MyCmdRunner implements CommandLineRunner {@Overridepublic void run(String... args) {System.out.println("CommandLineRunner執行");} }
3. 完整執行順序總結
以下是典型場景下各組件的執行順序:
- Bean構造函數 →?
@PostConstruct
?→?InitializingBean
?→?@Bean(initMethod)
ContextRefreshedEvent
?監聽器ApplicationRunner
?→?CommandLineRunner
4. 控制執行順序的方法
@Order
?注解:為ApplicationRunner
、CommandLineRunner
和事件監聽器指定優先級,值越小優先級越高。@DependsOn
?注解:強制指定Bean的依賴關系,間接影響初始化順序。- 實現
Ordered
接口:替代@Order
注解,動態控制順序。
5. 示例代碼驗證
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
輸出結果:
構造方法執行
@PostConstruct方法執行
InitializingBean的afterPropertiesSet執行
@Bean的initMethod執行
ContextRefreshedEvent事件觸發
ApplicationRunner執行
CommandLineRunner執行
通過理解這些執行順序,您可以更精準地安排初始化邏輯(如數據庫連接、緩存預熱等),避免因順序問題導致的依賴錯誤。