亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

介紹

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

方法一:注解

方案

  通過使用注解@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:

  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í),我們還可以通過類注解@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é)果

總結(jié)

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

相關(guān)文章

最新評(píng)論