1. 程式人生 > 程式設計 >SpringBoot專案啟動時如何讀取配置以及初始化資源

SpringBoot專案啟動時如何讀取配置以及初始化資源

介紹

  在開發過程中,我們有時候會遇到非介面呼叫而出發程式執行任務的一些場景,比如我們使用quartz定時框架通過配置檔案來啟動定時任務時,或者一些初始化資源場景等觸發的任務執行場景。

方法一:註解

方案

  通過使用註解@Configuration和@Bean來初始化資源,配置檔案當然還是通過@Value進行注入。

  • @Configuration:用於定義配置類,可替換xml配置檔案,被註解的類內部一般是包含了一個或者多個@Bean註解的方法。
  • @Bean:產生一個Bean物件,然後將Bean物件交給Spring管理,被註解的方法是會被AnnotationConfigApplicationContext或者AnnotationConfgWebApplicationContext掃描,用於構建bean定義,從而初始化Spring容器。產生這個物件的方法Spring只會呼叫一次,之後Spring就會將這個Bean物件放入自己的Ioc容器中。

補充@Configuration載入Spring:

  1. @Configuration配置spring並啟動spring容器
  2. @Configuration啟動容器+@Bean註冊Bean
  3. @Configuration啟動容器+@Component註冊Bean
  4. 使用 AnnotationConfigApplicationContext 註冊 AppContext 類的兩種方法
  5. 配置Web應用程式(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

方案

  實現CommandLineRunner介面,該介面中的Component會在所有Spring的Beans都初始化之後,在SpringApplication的run()之前執行。

  多個類需要有順序的初始化資源時,我們還可以通過類註解@Order(n)進行優先順序控制

示例

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);
 }
}

兩個示例的執行結果

SpringBoot專案啟動時如何讀取配置以及初始化資源

總結

到此這篇關於SpringBoot專案啟動時如何讀取配置以及初始化資源的文章就介紹到這了,更多相關SpringBoot啟動時讀取配置及初始化資源內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!