Spring @Order注解的使用小結(jié)
注解@Order或者接口Ordered的作用是定義Spring IOC容器中Bean的執(zhí)行順序的優(yōu)先級,而不是定義Bean的加載順序,Bean的加載順序不受@Order或Ordered接口的影響;
1.@Order的注解源碼解讀
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) @Documented public @interface Order { /** * 默認(rèn)是最低優(yōu)先級,值越小優(yōu)先級越高 */ int value() default Ordered.LOWEST_PRECEDENCE; }
- 注解可以作用在類(接口、枚舉)、方法、字段聲明(包括枚舉常量);
- 注解有一個int類型的參數(shù),可以不傳,默認(rèn)是最低優(yōu)先級;
- 通過常量類的值我們可以推測參數(shù)值越小優(yōu)先級越高;
2.Ordered接口類
package org.springframework.core; public interface Ordered { int HIGHEST_PRECEDENCE = -2147483648; int LOWEST_PRECEDENCE = 2147483647; int getOrder(); }
3.創(chuàng)建BlackPersion、YellowPersion類,這兩個類都實現(xiàn)CommandLineRunner
實現(xiàn)CommandLineRunner接口的類會在Spring IOC容器加載完畢后執(zhí)行,適合預(yù)加載類及其它資源;也可以使用ApplicationRunner,使用方法及效果是一樣的
package com.yaomy.common.order; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * @Description: Description * @ProjectName: spring-parent * @Version: 1.0 */ @Component @Order(1) public class BlackPersion implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("----BlackPersion----"); } }
package com.yaomy.common.order; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * @Description: Description * @ProjectName: spring-parent * @Version: 1.0 */ @Component @Order(0) public class YellowPersion implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("----YellowPersion----"); } }
4.啟動應(yīng)用程序打印出結(jié)果
----YellowPersion---- ----BlackPersion----
我們可以通過調(diào)整@Order的值來調(diào)整類執(zhí)行順序的優(yōu)先級,即執(zhí)行的先后;當(dāng)然也可以將@Order注解更換為Ordered接口,效果是一樣的
5.到這里可能會疑惑IOC容器是如何根據(jù)優(yōu)先級值來先后執(zhí)行程序的,那接下來看容器是如何加載component的
- 看如下的啟動main方法
@SpringBootApplication public class CommonBootStrap { public static void main(String[] args) { SpringApplication.run(CommonBootStrap.class, args); } }
這個不用過多的解釋,進入run方法…
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList(); this.configureHeadlessProperty(); SpringApplicationRunListeners listeners = this.getRunListeners(args); listeners.starting(); Collection exceptionReporters; try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments); this.configureIgnoreBeanInfo(environment); Banner printedBanner = this.printBanner(environment); context = this.createApplicationContext(); exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context); this.prepareContext(context, environment, listeners, applicationArguments, printedBanner); this.refreshContext(context); this.afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch); } listeners.started(context); //這里是重點,調(diào)用具體的執(zhí)行方法 this.callRunners(context, applicationArguments); } catch (Throwable var10) { this.handleRunFailure(context, var10, exceptionReporters, listeners); throw new IllegalStateException(var10); } try { listeners.running(context); return context; } catch (Throwable var9) { this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null); throw new IllegalStateException(var9); } } private void callRunners(ApplicationContext context, ApplicationArguments args) { List<Object> runners = new ArrayList(); runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); runners.addAll(context.getBeansOfType(CommandLineRunner.class).values()); //重點來了,按照定義的優(yōu)先級順序排序 AnnotationAwareOrderComparator.sort(runners); Iterator var4 = (new LinkedHashSet(runners)).iterator(); //循環(huán)調(diào)用具體方法 while(var4.hasNext()) { Object runner = var4.next(); if (runner instanceof ApplicationRunner) { this.callRunner((ApplicationRunner)runner, args); } if (runner instanceof CommandLineRunner) { this.callRunner((CommandLineRunner)runner, args); } } } private void callRunner(ApplicationRunner runner, ApplicationArguments args) { try { //執(zhí)行方法 runner.run(args); } catch (Exception var4) { throw new IllegalStateException("Failed to execute ApplicationRunner", var4); } } private void callRunner(CommandLineRunner runner, ApplicationArguments args) { try { //執(zhí)行方法 runner.run(args.getSourceArgs()); } catch (Exception var4) { throw new IllegalStateException("Failed to execute CommandLineRunner", var4); } }
到這里優(yōu)先級類的示例及其執(zhí)行原理都分析完畢;不過還是要強調(diào)下@Order、Ordered不影響類的加載順序而是影響B(tài)ean加載如IOC容器之后執(zhí)行的順序(優(yōu)先級);
個人理解是加載代碼的底層要支持優(yōu)先級執(zhí)行程序,否則即使配置上Ordered、@Order也是不起任何作用的,
個人的力量總是很微小的,歡迎大家來討論,一起努力成長?。?/p>
GitHub源碼:https://github.com/mingyang66/spring-parent
到此這篇關(guān)于Spring @Order注解的使用小結(jié)的文章就介紹到這了,更多相關(guān)Spring @Order注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA下創(chuàng)建SpringBoot+MyBatis+MySql項目實現(xiàn)動態(tài)登錄與注冊功能
這篇文章主要介紹了IDEA下創(chuàng)建SpringBoot+MyBatis+MySql項目實現(xiàn)動態(tài)登錄與注冊功能,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02springboot如何從數(shù)據(jù)庫獲取數(shù)據(jù),用echarts顯示(數(shù)據(jù)可視化)
這篇文章主要介紹了springboot如何從數(shù)據(jù)庫獲取數(shù)據(jù),用echarts顯示(數(shù)據(jù)可視化),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12Springboot 2.x中server.servlet.context-path的運用詳解
這篇文章主要介紹了Springboot 2.x中server.servlet.context-path的運用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01SpringBoot+VUE實現(xiàn)數(shù)據(jù)表格的實戰(zhàn)
本文將使用VUE+SpringBoot+MybatisPlus,以前后端分離的形式來實現(xiàn)數(shù)據(jù)表格在前端的渲染,具有一定的參考價值,感興趣的可以了解一下2021-08-08如何解決 Java 中的 IndexOutOfBoundsException 異
當(dāng)我們在 Java 中使用 List 的時候,有時候會出現(xiàn)向 List 中不存在的位置設(shè)置新元素的情況,從而導(dǎo)致 IndexOutOfBoundsException 異常,本文將會介紹這個問題的產(chǎn)生原因以及解決方案2023-10-10Java HashMap源碼及并發(fā)環(huán)境常見問題解決
這篇文章主要介紹了Java HashMap源碼及并發(fā)環(huán)境常見問題解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09