介紹
在開發(fā)過程中,我們有時(shí)候會(huì)遇到非接口調(diào)用而出發(fā)程序執(zhí)行任務(wù)的一些場景,比如我們使用quartz定時(shí)框架通過配置文件來啟動(dòng)定時(shí)任務(wù)時(shí),或者一些初始化資源場景等觸發(fā)的任務(wù)執(zhí)行場景。
方法一:注解
方案
通過使用注解@Configuration和@Bean來初始化資源,配置文件當(dāng)然還是通過@Value進(jìn)行注入。
- @Configuration:用于定義配置類,可替換xml配置文件,被注解的類內(nèi)部一般是包含了一個(gè)或者多個(gè)@Bean注解的方法。
- @Bean:產(chǎn)生一個(gè)Bean對(duì)象,然后將Bean對(duì)象交給Spring管理,被注解的方法是會(huì)被AnnotationConfigApplicationContext或者AnnotationConfgWebApplicationContext掃描,用于構(gòu)建bean定義,從而初始化Spring容器。產(chǎn)生這個(gè)對(duì)象的方法Spring只會(huì)調(diào)用一次,之后Spring就會(huì)將這個(gè)Bean對(duì)象放入自己的Ioc容器中。
補(bǔ)充@Configuration加載Spring:
- @Configuration配置spring并啟動(dòng)spring容器
- @Configuration啟動(dòng)容器+@Bean注冊(cè)Bean
- @Configuration啟動(dòng)容器+@Component注冊(cè)Bean
- 使用 AnnotationConfigApplicationContext 注冊(cè) AppContext 類的兩種方法
- 配置Web應(yīng)用程序(web.xml中配置AnnotationConfigApplicationContext)
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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í),我們還可以通過類注解@Order(n)進(jìn)行優(yōu)先級(jí)控制
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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é)果
總結(jié)
到此這篇關(guān)于SpringBoot項(xiàng)目啟動(dòng)時(shí)如何讀取配置以及初始化資源的文章就介紹到這了,更多相關(guān)SpringBoot啟動(dòng)時(shí)讀取配置及初始化資源內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/Andya/p/13187845.html