Spring @Order注解的使用小結(jié)
注解@Order或者接口Ordered的作用是定義Spring IOC容器中Bean的執(zhí)行順序的優(yōu)先級(jí),而不是定義Bean的加載順序,Bean的加載順序不受@Order或Ordered接口的影響;
1.@Order的注解源碼解讀
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {
/**
* 默認(rèn)是最低優(yōu)先級(jí),值越小優(yōu)先級(jí)越高
*/
int value() default Ordered.LOWEST_PRECEDENCE;
}
- 注解可以作用在類(lèi)(接口、枚舉)、方法、字段聲明(包括枚舉常量);
- 注解有一個(gè)int類(lèi)型的參數(shù),可以不傳,默認(rèn)是最低優(yōu)先級(jí);
- 通過(guò)常量類(lèi)的值我們可以推測(cè)參數(shù)值越小優(yōu)先級(jí)越高;
2.Ordered接口類(lèi)
package org.springframework.core;
public interface Ordered {
int HIGHEST_PRECEDENCE = -2147483648;
int LOWEST_PRECEDENCE = 2147483647;
int getOrder();
}
3.創(chuàng)建BlackPersion、YellowPersion類(lèi),這兩個(gè)類(lèi)都實(shí)現(xiàn)CommandLineRunner
實(shí)現(xiàn)CommandLineRunner接口的類(lèi)會(huì)在Spring IOC容器加載完畢后執(zhí)行,適合預(yù)加載類(lèi)及其它資源;也可以使用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.啟動(dòng)應(yīng)用程序打印出結(jié)果
----YellowPersion---- ----BlackPersion----
我們可以通過(guò)調(diào)整@Order的值來(lái)調(diào)整類(lèi)執(zhí)行順序的優(yōu)先級(jí),即執(zhí)行的先后;當(dāng)然也可以將@Order注解更換為Ordered接口,效果是一樣的
5.到這里可能會(huì)疑惑IOC容器是如何根據(jù)優(yōu)先級(jí)值來(lái)先后執(zhí)行程序的,那接下來(lái)看容器是如何加載component的
- 看如下的啟動(dòng)main方法
@SpringBootApplication
public class CommonBootStrap {
public static void main(String[] args) {
SpringApplication.run(CommonBootStrap.class, args);
}
}
這個(gè)不用過(guò)多的解釋?zhuān)M(jìn)入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ǎn),調(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());
//重點(diǎn)來(lái)了,按照定義的優(yōu)先級(jí)順序排序
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)先級(jí)類(lèi)的示例及其執(zhí)行原理都分析完畢;不過(guò)還是要強(qiáng)調(diào)下@Order、Ordered不影響類(lèi)的加載順序而是影響B(tài)ean加載如IOC容器之后執(zhí)行的順序(優(yōu)先級(jí));
個(gè)人理解是加載代碼的底層要支持優(yōu)先級(jí)執(zhí)行程序,否則即使配置上Ordered、@Order也是不起任何作用的,
個(gè)人的力量總是很微小的,歡迎大家來(lái)討論,一起努力成長(zhǎng)??!
GitHub源碼:https://github.com/mingyang66/spring-parent
到此這篇關(guān)于Spring @Order注解的使用小結(jié)的文章就介紹到這了,更多相關(guān)Spring @Order注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot+element-ui實(shí)現(xiàn)多文件一次上傳功能
這篇文章主要介紹了springboot+element-ui多文件一次上傳功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
SpringBoot中9個(gè)內(nèi)置過(guò)濾器用法的完整指南
這篇文章主要為大家詳細(xì)介紹了SpringBoot中9個(gè)內(nèi)置過(guò)濾器用法的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一2025-08-08
springboot使用redis緩存亂碼(key或者value亂碼)的解決
在通過(guò)springboot緩存數(shù)據(jù)的時(shí)候,發(fā)現(xiàn)key是一堆很不友好的東西,本文主要介紹了springboot使用redis緩存亂碼(key或者value亂碼)的解決,感興趣的可以了解一下2023-11-11
springboot創(chuàng)建監(jiān)聽(tīng)和處理事件的操作方法
這篇文章主要介紹了springboot創(chuàng)建監(jiān)聽(tīng)和處理事件的操作方法,使用Spring Boot的事件機(jī)制來(lái)監(jiān)聽(tīng)和處理事件有多種優(yōu)勢(shì),本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2024-07-07
springboot 啟動(dòng)時(shí)初始化數(shù)據(jù)庫(kù)的步驟
這篇文章主要介紹了springboot 啟動(dòng)時(shí)初始化數(shù)據(jù)庫(kù)的步驟,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2021-01-01
Java實(shí)現(xiàn)整合文件上傳到FastDFS的方法詳細(xì)
FastDFS是一個(gè)開(kāi)源的輕量級(jí)分布式文件系統(tǒng),對(duì)文件進(jìn)行管理,功能包括:文件存儲(chǔ)、文件同步、文件上傳、文件下載等,解決了大容量存儲(chǔ)和負(fù)載均衡的問(wèn)題。本文將提供Java將文件上傳至FastDFS的示例代碼,需要的參考一下2022-02-02
Java使用DateTimeFormatter實(shí)現(xiàn)格式化時(shí)間
這篇文章主要介紹了Java使用DateTimeFormatter實(shí)現(xiàn)格式化時(shí)間,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01

