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

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

 更新時間:2020年06月26日 11:29:58   作者:Andya_net  
這篇文章主要給大家介紹了關(guān)于SpringBoot項目啟動時如何讀取配置以及初始化資源的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者使用SpringBoot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

介紹

  在開發(fā)過程中,我們有時候會遇到非接口調(diào)用而出發(fā)程序執(zhí)行任務(wù)的一些場景,比如我們使用quartz定時框架通過配置文件來啟動定時任務(wù)時,或者一些初始化資源場景等觸發(fā)的任務(wù)執(zhí)行場景。

方法一:注解

方案

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

  • @Configuration:用于定義配置類,可替換xml配置文件,被注解的類內(nèi)部一般是包含了一個或者多個@Bean注解的方法。
  • @Bean:產(chǎn)生一個Bean對象,然后將Bean對象交給Spring管理,被注解的方法是會被AnnotationConfigApplicationContext或者AnnotationConfgWebApplicationContext掃描,用于構(gòu)建bean定義,從而初始化Spring容器。產(chǎn)生這個對象的方法Spring只會調(diào)用一次,之后Spring就會將這個Bean對象放入自己的Ioc容器中。

補充@Configuration加載Spring:

  1. @Configuration配置spring并啟動spring容器
  2. @Configuration啟動容器+@Bean注冊Bean
  3. @Configuration啟動容器+@Component注冊Bean
  4. 使用 AnnotationConfigApplicationContext 注冊 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

方案

  實現(xiàn)CommandLineRunner接口,該接口中的Component會在所有Spring的Beans都初始化之后,在SpringApplication的run()之前執(zhí)行。

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

示例

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

兩個示例的運行結(jié)果

總結(jié)

到此這篇關(guān)于SpringBoot項目啟動時如何讀取配置以及初始化資源的文章就介紹到這了,更多相關(guān)SpringBoot啟動時讀取配置及初始化資源內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

抚松县| 六盘水市| 涞源县| 旌德县| 南宁市| 宝清县| 高邮市| 临沭县| 苏尼特左旗| 修文县| 奎屯市| 嘉兴市| 扎赉特旗| 定州市| 兰州市| 台南县| 奈曼旗| 中卫市| 盘锦市| 贵南县| 大新县| 苍溪县| 石首市| 鹤壁市| 浦城县| 玉门市| 石城县| 尉氏县| 休宁县| 敖汉旗| 邹城市| 横峰县| 得荣县| 凤阳县| 梅州市| 鄂尔多斯市| 宁德市| 京山县| 泾川县| 隆德县| 时尚|