溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot項(xiàng)目啟動(dòng)時(shí)讀取配置以及初始化資源的方法

發(fā)布時(shí)間:2020-06-28 13:46:49 來(lái)源:億速云 閱讀:235 作者:清晨 欄目:開(kāi)發(fā)技術(shù)

小編給大家分享一下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)行注入。

  • @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:

  1. @Configuration配置spring并啟動(dòng)spring容器
  2. @Configuration啟動(dòng)容器+@Bean注冊(cè)Bean
  3. @Configuration啟動(dòng)容器+@Component注冊(cè)Bean
  4. 使用 AnnotationConfigApplicationContext 注冊(cè) AppContext 類的兩種方法
  5. 配置Web應(yīng)用程序(web.xml中配置AnnotationConfigApplicationContext)
     

示例

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é)果

SpringBoot項(xiàng)目啟動(dòng)時(shí)讀取配置以及初始化資源的方法

看完了這篇文章,相信你對(duì)SpringBoot項(xiàng)目啟動(dòng)時(shí)讀取配置以及初始化資源的方法有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI