您好,登錄后才能下訂單哦!
小編給大家分享一下SpringBoot項(xiàng)目啟動(dòng)時(shí)讀取配置以及初始化資源的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討方法吧!
介紹
  在開(kāi)發(fā)過(guò)程中,我們有時(shí)候會(huì)遇到非接口調(diào)用而出發(fā)程序執(zhí)行任務(wù)的一些場(chǎng)景,比如我們使用quartz定時(shí)框架通過(guò)配置文件來(lái)啟動(dòng)定時(shí)任務(wù)時(shí),或者一些初始化資源場(chǎng)景等觸發(fā)的任務(wù)執(zhí)行場(chǎng)景。
方法一:注解
方案
  通過(guò)使用注解@Configuration和@Bean來(lái)初始化資源,配置文件當(dāng)然還是通過(guò)@Value進(jìn)行注入。
補(bǔ)充@Configuration加載Spring:
示例
package com.example.andya.demo.conf; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author andya * @create 2020-06-24 14:37 */ @Configuration public class InitConfigTest { @Value("${key}") private String key; @Bean public String testInit(){ System.out.println("init key: " + key); return key; } }
方法二:CommandLineRunner
方案
  實(shí)現(xiàn)CommandLineRunner接口,該接口中的Component會(huì)在所有Spring的Beans都初始化之后,在SpringApplication的run()之前執(zhí)行。
  多個(gè)類需要有順序的初始化資源時(shí),我們還可以通過(guò)類注解@Order(n)進(jìn)行優(yōu)先級(jí)控制
示例
package com.example.andya.demo.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * @author andya * @create 2020-06-24 14:47 */ @Component public class CommandLineRunnerTest implements CommandLineRunner { @Value("${key}") private String key; @Override public void run(String... strings) throws Exception { System.out.println("command line runner, init key: " + key); } }
兩個(gè)示例的運(yùn)行結(jié)果
看完了這篇文章,相信你對(duì)SpringBoot項(xiàng)目啟動(dòng)時(shí)讀取配置以及初始化資源的方法有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。