最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

應(yīng)用啟動數(shù)據(jù)初始化接口CommandLineRunner和Application詳解

 更新時間:2021年12月21日 14:41:40   作者:晴空排云  
這篇文章主要介紹了應(yīng)用啟動數(shù)據(jù)初始化接口CommandLineRunner和Application詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

應(yīng)用啟動數(shù)據(jù)初始化接口CommandLineRunner和Application詳解

在SpringBoot項目中創(chuàng)建組件類實現(xiàn)CommandLineRunner或ApplicationRunner接口可實現(xiàn)在應(yīng)用啟動之后及時進行一些初始化操作,如緩存預(yù)熱、索引重建等等類似一些數(shù)據(jù)初始化操作。

兩個接口功能相同,都有個run方法需要重寫,只是實現(xiàn)方法的參數(shù)不同。

CommandLineRunner接收原始的命令行啟動參數(shù),ApplicationRunner則將啟動參數(shù)對象化。

1 運行時機

兩個接口都是在SpringBoot應(yīng)用初始化好上下文之后運行,所以在運行過程中,可以使用上下文中的所有信息,例如一些Bean等等。在框架SpringApplication類源碼的run方法中,可查看Runner的調(diào)用時機callRunners,如下:

/**
 * Run the Spring application, creating and refreshing a new
 * {@link ApplicationContext}.
 * @param args the application arguments (usually passed from a Java main method)
 * @return a running {@link ApplicationContext}
 */
public ConfigurableApplicationContext run(String... args) {
	StopWatch stopWatch = new StopWatch();
	stopWatch.start();
	ConfigurableApplicationContext context = null;
	Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
	configureHeadlessProperty();
	SpringApplicationRunListeners listeners = getRunListeners(args);
	listeners.starting();
	try {
		ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
		ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
		configureIgnoreBeanInfo(environment);
		Banner printedBanner = printBanner(environment);
		context = createApplicationContext();
		exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
				new Class[] { ConfigurableApplicationContext.class }, context);
		prepareContext(context, environment, listeners, applicationArguments, printedBanner);
		refreshContext(context);
		afterRefresh(context, applicationArguments);
		stopWatch.stop();
		if (this.logStartupInfo) {
			new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
		}
		listeners.started(context);
		//調(diào)用Runner,執(zhí)行初始化操作
		callRunners(context, applicationArguments);
	}
	catch (Throwable ex) {
		handleRunFailure(context, ex, exceptionReporters, listeners);
		throw new IllegalStateException(ex);
	}
	try {
		listeners.running(context);
	}
	catch (Throwable ex) {
		handleRunFailure(context, ex, exceptionReporters, null);
		throw new IllegalStateException(ex);
	}
	return context;
}

2 實現(xiàn)接口

2.1 CommandLineRunner

簡單實現(xiàn)如下,打印啟動參數(shù)信息:

@Order(1)
@Component
public class CommandLineRunnerInit implements CommandLineRunner {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private final String LOG_PREFIX = ">>>>>>>>>>CommandLineRunner >>>>>>>>>> ";
    @Override
    public void run(String... args) throws Exception {
        try {
            this.logger.error("{} args:{}", LOG_PREFIX, StringUtils.join(args, ","));
        } catch (Exception e) {
            logger.error("CommandLineRunnerInit run failed", e);
        }
    }
}

2.2 ApplicationRunner

簡單實現(xiàn)如下,打印啟動參數(shù)信息,并調(diào)用Bean的方法(查詢用戶數(shù)量):

@Order(2)
@Component
public class ApplicationRunnerInit implements ApplicationRunner {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private final String LOG_PREFIX = ">>>>>>>>>>ApplicationRunner >>>>>>>>>> ";
    private final UserRepository userRepository;
    public ApplicationRunnerInit(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            this.logger.error("{} args:{}", LOG_PREFIX, JSONObject.toJSONString(args));
            for (String optionName : args.getOptionNames()) {
                this.logger.error("{} argName:{} argValue:{}", LOG_PREFIX, optionName, args.getOptionValues(optionName));
            }
            this.logger.error("{} user count:{}", LOG_PREFIX, this.userRepository.count());
        } catch (Exception e) {
            logger.error("CommandLineRunnerInit run failed", e);
        }
    }
}

3 執(zhí)行順序

如果實現(xiàn)了多個Runner,默認會按照添加順序先執(zhí)行ApplicationRunner的實現(xiàn)再執(zhí)行CommandLineRunner的實現(xiàn),如果多個Runner之間的初始化邏輯有先后順序,可在實現(xiàn)類添加@Order注解設(shè)置執(zhí)行順序,可在源碼SpringApplication類的callRunners方法中查看,如下:

private void callRunners(ApplicationContext context, ApplicationArguments args) {
 List<Object> runners = new ArrayList<>();
 //先添加的ApplicationRunner實現(xiàn)
 runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
 //再添加的CommandLineRunner實現(xiàn)
 runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
 //如果設(shè)置了順序,則按設(shè)定順序重新排序
 AnnotationAwareOrderComparator.sort(runners);
 for (Object runner : new LinkedHashSet<>(runners)) {
  if (runner instanceof ApplicationRunner) {
   callRunner((ApplicationRunner) runner, args);
  }
  if (runner instanceof CommandLineRunner) {
   callRunner((CommandLineRunner) runner, args);
  }
 }
}

4 設(shè)置啟動參數(shù)

為了便于對比效果,在Idea中設(shè)置啟動參數(shù)如下圖(生產(chǎn)環(huán)境中會自動讀取命令行啟動參數(shù)):

在這里插入圖片描述

5 運行效果

在上面的兩個Runner中,設(shè)定了CommandLineRunnerInit是第一個,ApplicationRunnerInit是第二個。啟動應(yīng)用,運行效果如下圖:

在這里插入圖片描述

ApplicationRunner和CommandLineRunner用法區(qū)別

業(yè)務(wù)場景:

應(yīng)用服務(wù)啟動時,加載一些數(shù)據(jù)和執(zhí)行一些應(yīng)用的初始化動作。如:刪除臨時文件,清除緩存信息,讀取配置文件信息,數(shù)據(jù)庫連接等。

1、SpringBoot提供了CommandLineRunner和ApplicationRunner接口。當(dāng)接口有多個實現(xiàn)類時,提供了@order注解實現(xiàn)自定義執(zhí)行順序,也可以實現(xiàn)Ordered接口來自定義順序。

注意:數(shù)字越小,優(yōu)先級越高,也就是@Order(1)注解的類會在@Order(2)注解的類之前執(zhí)行。

兩者的區(qū)別在于:

ApplicationRunner中run方法的參數(shù)為ApplicationArguments,而CommandLineRunner接口中run方法的參數(shù)為String數(shù)組。想要更詳細地獲取命令行參數(shù),那就使用ApplicationRunner接口

ApplicationRunner

@Component
@Order(value = 10)
public class AgentApplicationRun2 implements ApplicationRunner {
 @Override
 public void run(ApplicationArguments applicationArguments) throws Exception {
 }
}

CommandLineRunner

@Component
@Order(value = 11)
public class AgentApplicationRun implements CommandLineRunner {
 @Override
 public void run(String... strings) throws Exception {
 }
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Spring中的事務(wù)操作、注解及XML配置詳解

    Spring中的事務(wù)操作、注解及XML配置詳解

    這篇文章主要給大家介紹了關(guān)于Spring中事務(wù)操作、注解及XML配置的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • SpringBoot如何集成Netty

    SpringBoot如何集成Netty

    這篇文章主要介紹了SpringBoot如何集成Netty問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • springboot自定義Starter過程解析

    springboot自定義Starter過程解析

    這篇文章主要介紹了springboot自定義Starter過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • SpringBoot中的ApplicationRunner與CommandLineRunner問題

    SpringBoot中的ApplicationRunner與CommandLineRunner問題

    這篇文章主要介紹了SpringBoot中的ApplicationRunner與CommandLineRunner問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • Dubbo3的Spring適配原理與初始化流程源碼解析

    Dubbo3的Spring適配原理與初始化流程源碼解析

    這篇文章主要為大家介紹了Dubbo3的Spring適配原理與初始化流程源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • Java實現(xiàn)圖片倒影的源碼實例內(nèi)容

    Java實現(xiàn)圖片倒影的源碼實例內(nèi)容

    在本篇文章里小編給大家整理的是關(guān)于Java實現(xiàn)圖片倒影的源碼以及相關(guān)知識點,有需要的朋友們學(xué)習(xí)下。
    2019-09-09
  • java取某段/某個時間段的值的方法

    java取某段/某個時間段的值的方法

    這篇文章主要介紹了java取某段/某個時間段的值的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Java的NIO之通道channel詳解

    Java的NIO之通道channel詳解

    這篇文章主要介紹了Java的NIO之通道channel詳解,通道channel由java.nio.channels 包定義的,Channel 表示IO源與目標打開的連接,Channel類類似于傳統(tǒng)的"流",只不過Channel本身不能直接訪問數(shù)據(jù),Channel只能與Buffer進行交互,需要的朋友可以參考下
    2023-10-10
  • 如何基于SpringWeb?MultipartFile實現(xiàn)文件上傳、下載功能

    如何基于SpringWeb?MultipartFile實現(xiàn)文件上傳、下載功能

    在做項目時,后端經(jīng)常采用上傳文件組件MultipartFile,下面這篇文章主要給大家介紹了關(guān)于如何基于SpringWeb?MultipartFile實現(xiàn)文件上傳、下載功能的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-07-07
  • Java中自定義泛型方法及其應(yīng)用示例代碼

    Java中自定義泛型方法及其應(yīng)用示例代碼

    泛型方法是Java中一個強大的特性,它允許我們在方法級別使用類型參數(shù),提高代碼的復(fù)用性和類型安全性,通過本文,讀者可以學(xué)習(xí)如何定義和使用泛型方法,并了解其在處理集合、比較對象、創(chuàng)建實例等任務(wù)中的應(yīng)用,感興趣的朋友一起看看吧
    2025-02-02

最新評論

长乐市| 左贡县| 朝阳市| 留坝县| 连江县| 深圳市| 资源县| 西林县| 鸡西市| 柞水县| 内乡县| 新巴尔虎左旗| 营山县| 嘉峪关市| 延边| 搜索| 黔东| 亚东县| 沾益县| 石阡县| 呼玛县| 监利县| 井陉县| 紫阳县| 淄博市| 铜山县| 防城港市| 通许县| 东宁县| 施秉县| 巴林左旗| 神农架林区| 陆良县| 刚察县| 阳曲县| 大连市| 宁南县| 达拉特旗| 芦溪县| 怀远县| 五指山市|