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

SpringBoot讀取配置文件常用方法解析

 更新時(shí)間:2020年08月13日 10:07:30   作者:Chsoul  
這篇文章主要介紹了SpringBoot讀取配置文件常用方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

首先回憶一下在沒(méi)有使用SpringBoot之前也就是傳統(tǒng)的spring項(xiàng)目中是如何讀取配置文件,通過(guò)I/O流讀取指定路徑的配置文件,然后再去獲取指定的配置信息。

傳統(tǒng)項(xiàng)目讀取配置方式

讀取xml配置文件

 public String readFromXml(String xmlPath, String property) {
  SAXReader reader = new SAXReader();
  Document doc = null;
  try {
   doc = reader.read(new File(xmlPath));
  } catch (DocumentException e) {
   e.printStackTrace();
  }
  Iterator<Element> iterator = doc.getRootElement().elementIterator();
  while (iterator.hasNext()){
   Element element = iterator.next();
   if (element.getQName().getName().equals(property)){
    return element.getTextTrim();
   }
  }
  return null;
 }

讀取.properties配置文件

 public String readFromProperty(String filePath, String property) {
  Properties prop = new Properties();
  try {
   prop.load(new FileInputStream(filePath));
   String value = prop.getProperty(property);
   if (value != null) {
    return value;
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }

SpringBoot讀取配置方式

如何使用SpringBoot讀取配置文件,從使用Spring慢慢演變,但是本質(zhì)原理是一樣的,只是SpringBoot簡(jiǎn)化配置,通過(guò)注解簡(jiǎn)化開(kāi)發(fā),接下來(lái)介紹一些常用注解。

@ImportResource注解

這個(gè)注解用來(lái)導(dǎo)入Spring的配置文件,是配置文件中的內(nèi)容注入到配置類(lèi)中,參數(shù)是一個(gè)數(shù)組,可以注入多個(gè)配置文件

代碼演示:

在SpringBoot項(xiàng)目的resources目錄下創(chuàng)建一個(gè)xml配置文件beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 <bean id="configBean" class="com.example.test.config.ConfigBean">
  <property name="dbType" value="Oracle"/>
  <property name="driverClassName" value="jdbc.driver.Oracle.OracleDriver"/>
  <property name="host" value="127.0.0.1"/>
  <property name="userName" value="oracle"/>
  <property name="password" value="oracle"/>
 </bean>
</beans>

創(chuàng)建配置類(lèi)ConfigBean

package com.example.test.config;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @author Vincente
 * @date 2020/07/12-12:29
 * @desc 配置類(lèi)
 **/
@Setter
@Getter
@ToString
public class ConfigBean {
 private String dbType;
 private String driverClassName;
 private String host;
 private String userName;
 private String password;
}

添加@ImportResource注解,在SpringBoot項(xiàng)目的啟動(dòng)類(lèi)添加

package com.example.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class TestApplication {

 public static void main(String[] args) {
  SpringApplication.run(TestApplication.class, args);
 }
}

測(cè)試代碼

package com.example.test;

import com.example.test.config.ConfigBean;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)

class TestApplicationTests {
 @Autowired
 private ConfigBean configBean;
 @Test
 void testConfigBean(){
  System.out.println(configBean);
 }
}

輸出結(jié)果

ConfigBean(dbType=Oracle, driverClassName=jdbc.driver.Oracle.OracleDriver, host=127.0.0.1, userName=oracle, password=oracle)

小結(jié) @ImportResource注解可以用來(lái)加載一個(gè)外部xml文件,注入到項(xiàng)目完成配置,但是這樣引入xml并沒(méi)有達(dá)到SpringBoot簡(jiǎn)化配置的目的。

@Configuration和@Bean注解#

@Configuration和@Bean注解并不能讀取配置文件中的信息,但是這兩個(gè)類(lèi)本身用來(lái)定義配置類(lèi)

@Configuration用來(lái)代替xml文件,添加在一個(gè)類(lèi)上面

@Bean用來(lái)代替bean標(biāo)簽,聲明在方法上,方法的返回值返回一個(gè)對(duì)象到Spring的IoC容器中,方法名稱(chēng)相當(dāng)于bean標(biāo)簽中的ID

代碼樣例

聲明一個(gè)bean

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Vincente
 * @date 2020/07/12-13:28
 * @desc
 **/
@Configuration
public class RestTemplateConfig {
 @Bean
 public RestTemplateConfig restTemplate(){
  return new RestTemplate();
 }
}

測(cè)試代碼

package com.example.test;

import com.example.test.config.RestTemplateConfig;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@SpringBootTest
@RunWith(SpringRunner.class)

class TestApplicationTests {
 @Resource
 private RestTemplateConfig restTemplate;

 @Test
 void testConfigBean(){
  System.out.println(restTemplate);
 }
}

輸出結(jié)果

com.example.test.config.RestTemplateConfig@de7e193

@Import注解

@Import注解是用來(lái)導(dǎo)入配置類(lèi)或者一些需要前置加載的類(lèi),帶有@Configuration的配置類(lèi)(4.2 版本之前只可以導(dǎo)入配置類(lèi),4.2版本之后 也可以導(dǎo)入 普通類(lèi))

代碼樣例

結(jié)合上面的代碼做修改,不全部貼出

將RestTemplateConfigestTemplateConfig類(lèi)中的@Configuration注解去掉,在ConfigBean中導(dǎo)入

@Setter
@Getter
@ToString
@Import(RestTemplateConfig.class)
public class ConfigBean {
 private String dbType;
 private String driverClassName;
 private String host;
 private String userName;
 private String password;
}

測(cè)試代碼

package com.example.test;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@SpringBootTest
@RunWith(SpringRunner.class)

class TestApplicationTests {
 @Resource
 ApplicationContext ctx;

 @Test
 void testConfigBean(){
  System.out.println(ctx.getBean("restTemplate"));
 }
}

輸出結(jié)果

com.example.test.config.RestTemplateConfig@6cd15072

小結(jié) 可以看到在IoC容器中已經(jīng)導(dǎo)入了RestTemplateConfig(普通)類(lèi),這個(gè)注解類(lèi)似于之前applicationContext.xml中的import標(biāo)簽

@ConfigurationProperties和@Value#

@ConfigurationProperties和@Value這兩個(gè)注解算是在SpringBoot中用的比較多的注解了,可以在項(xiàng)目的配置文件application.yml和application.properties中直接讀取配置,但是在用法上二者也是有一定的區(qū)別

代碼樣例

創(chuàng)建配置文件application.yml

db-config:
 db-type: Oracle
 driver-class-name: jdbc.driver.Ooracle.OracleDriver
 host: 127.0.0.1
 user-name: Oracle
 password: Oracle

server:
 port: 8080

創(chuàng)建配置類(lèi)ConfigBean

package com.example.test.config;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author Vincente
 * @date 2020/07/12-12:29
 * @desc 配置類(lèi)
 **/
@Setter
@Getter
@ToString
@ConfigurationProperties(prefix = "db-config")
public class ConfigBean {
 private String dbType;
 private String driverClassName;
 private String host;
 private String userName;
 private String password;
}

測(cè)試代碼

package com.example.test;

import com.example.test.config.ConfigBean;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@SpringBootTest
@RunWith(SpringRunner.class)

class TestApplicationTests {
 @Resource
 ConfigBean configBean;
 @Value("${server.port}")
 private String port;

 @Test
 void testConfigBean(){
  System.out.println(configBean);
  System.out.println(port);
 }
}

輸出結(jié)果

ConfigBean(dbType=Oracle, driverClassName=jdbc.driver.Ooracle.OracleDriver, host=127.0.0.1, userName=Oracle, password=Oracle)
8080

-總結(jié) 二者的一些區(qū)別

特性 @ConfigurationProperties @Value
SpEL表達(dá)式 不支持 支持
屬性松散綁定 支持 不支持
JSR303數(shù)據(jù)校驗(yàn) 支持 不支持

添加校驗(yàn)注解

package com.example.test.config;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Null;

/**
 * @author Vincente
 * @date 2020/07/12-12:29
 * @desc 配置類(lèi)
 **/
@Setter
@Getter
@ToString
@ConfigurationProperties(prefix = "db-config")
@Validated
public class ConfigBean {
 @Null
 private String dbType;
 private String driverClassName;
 private String host;
 private String userName;
 private String password;
}

輸出結(jié)果

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'db-config' to com.example.test.config.ConfigBean failed:

 Property: db-config.dbType
 Value: Oracle
 Origin: class path resource [application.yml]:2:12
 Reason: 必須為null

@PropertySource注解

@ConfigurationProperties和@Value這兩個(gè)注解默認(rèn)從項(xiàng)目的主配置文件中讀取配置,當(dāng)項(xiàng)目配置較多全部從一個(gè)地方讀取會(huì)顯得臃腫,可以將配置文件按照模塊拆分讀取到不同的配置類(lèi)中,可以使用@PropertySource配合@Value讀取其他配置文件

代碼樣例

創(chuàng)建配置文件db-config.yml

/**
 * @author Vincente
 * @date 2020/07/12-14:19
 * @desc
 **/
db-config:
 db-type: Oracle
 driver-class-name: jdbc.driver.Ooracle.OracleDriver
 host: 127.0.0.1
 user-name: Oracle
 password: Oracle

創(chuàng)建配置類(lèi)ConfigBean

package com.example.test.config;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @author Vincente
 * @date 2020/07/12-12:29
 * @desc 配置類(lèi)
 **/
@Setter
@Getter
@ToString
@PropertySource("classpath:db-config.yml")
@Component
public class ConfigBean {
 @Value("${db-type}")
 private String dbType;
 @Value("${driver-class-name}")
 private String driverClassName;
 @Value("${host}")
 private String host;
 @Value("${user-name}")
 private String userName;
 @Value("${password}")
 private String password;
}

測(cè)試代碼

package com.example.test;

import com.example.test.config.ConfigBean;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@SpringBootTest
@RunWith(SpringRunner.class)

class TestApplicationTests {
 @Resource
 ConfigBean configBean;

 @Test
 void testConfigBean(){
  System.out.println(configBean);
 }
}

輸出結(jié)果

ConfigBean(dbType=Oracle, driverClassName=jdbc.driver.Ooracle.OracleDriver, host=127.0.0.1, userName=Vincente, password=Oracle)

小結(jié)

@PropertySource 用于獲取類(lèi)路徑下的db-config.yml配置文件,@Value用于獲取yml中的配置信息,@Component注解用來(lái)將配置類(lèi)交給Spring容器管理

總結(jié)

SpringBoot中提供了注解代替配置文件的方式來(lái)獲取項(xiàng)目中的配置,大大簡(jiǎn)化了開(kāi)發(fā),以上總結(jié)了常用的讀取配置的方法,簡(jiǎn)單來(lái)說(shuō)就是兩種文件(yml和properties)幾大注解(@Value,@PropertySource,@Configuration,@ConfigurationProperties,@Import,@Bean);首先要了解每個(gè)注解的使用場(chǎng)景后,其次根據(jù)項(xiàng)目實(shí)際情況來(lái)具體的使用

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • spring四種依賴(lài)注入方式的詳細(xì)介紹

    spring四種依賴(lài)注入方式的詳細(xì)介紹

    本篇文章主要介紹了spring四種依賴(lài)注入方式的詳細(xì)介紹,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-02-02
  • Maven直接依賴(lài)、間接依賴(lài)、依賴(lài)沖突、依賴(lài)仲裁的實(shí)現(xiàn)

    Maven直接依賴(lài)、間接依賴(lài)、依賴(lài)沖突、依賴(lài)仲裁的實(shí)現(xiàn)

    本文主要介紹了Maven直接依賴(lài)、間接依賴(lài)、依賴(lài)沖突、依賴(lài)仲裁的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-09-09
  • 淺析Spring Boot中的spring-boot-load模塊

    淺析Spring Boot中的spring-boot-load模塊

    spring-boot-loader模塊允許我們使用java -jar archive.jar運(yùn)行包含嵌套依賴(lài)jar的jar或者war文件,它提供了三種類(lèi)啟動(dòng)器。下面通過(guò)本文給大家介紹spring-boot-load模塊的相關(guān)知識(shí),感興趣的朋友一起看看吧
    2018-01-01
  • java操作mysql實(shí)現(xiàn)增刪改查的方法

    java操作mysql實(shí)現(xiàn)增刪改查的方法

    這篇文章主要介紹了java操作mysql實(shí)現(xiàn)增刪改查的方法,結(jié)合實(shí)例形式分析了java操作mysql數(shù)據(jù)庫(kù)進(jìn)行增刪改查的具體實(shí)現(xiàn)技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2017-05-05
  • IDEA的Web項(xiàng)目右鍵無(wú)法創(chuàng)建Servlet問(wèn)題解決辦法

    IDEA的Web項(xiàng)目右鍵無(wú)法創(chuàng)建Servlet問(wèn)題解決辦法

    這篇文章主要介紹了IDEA的Web項(xiàng)目右鍵無(wú)法創(chuàng)建Servlet問(wèn)題解決辦法的相關(guān)資料,在IDEA中新建Servlet時(shí)發(fā)現(xiàn)缺失選項(xiàng),可以通過(guò)在pom.xml文件中添加servlet依賴(lài)解決,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2024-10-10
  • 在Mac上安裝JDK21的詳細(xì)流程

    在Mac上安裝JDK21的詳細(xì)流程

    在macOS上安裝JDK(Java Development Kit)21是相對(duì)簡(jiǎn)單的過(guò)程,這篇文章主要給大家介紹了關(guān)于在Mac上安裝JDK21的詳細(xì)流程,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2024-08-08
  • SpringBoot結(jié)合Swagger2自動(dòng)生成api文檔的方法

    SpringBoot結(jié)合Swagger2自動(dòng)生成api文檔的方法

    這篇文章主要介紹了SpringBoot結(jié)合Swagger2自動(dòng)生成api文檔的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-05-05
  • scala 讀取txt文件的方法示例

    scala 讀取txt文件的方法示例

    這篇文章主要介紹了scala 讀取txt文件的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • SpringBoot2.x入門(mén)教程之引入jdbc模塊與JdbcTemplate簡(jiǎn)單使用方法

    SpringBoot2.x入門(mén)教程之引入jdbc模塊與JdbcTemplate簡(jiǎn)單使用方法

    這篇文章主要介紹了SpringBoot2.x入門(mén)教程之引入jdbc模塊與JdbcTemplate簡(jiǎn)單使用方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-07-07
  • java對(duì)接支付寶支付接口開(kāi)發(fā)詳細(xì)步驟

    java對(duì)接支付寶支付接口開(kāi)發(fā)詳細(xì)步驟

    本文主要介紹了java對(duì)接支付寶支付接口開(kāi)發(fā)詳細(xì)步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-01-01

最新評(píng)論

尚义县| 策勒县| 荔波县| 兴宁市| 金昌市| 玉山县| 涞源县| 车致| 济宁市| 绩溪县| 确山县| 无锡市| 福安市| 济源市| 上栗县| 曲阜市| 克拉玛依市| 辛集市| 城口县| 亚东县| 四川省| 汕头市| 工布江达县| 南阳市| 马尔康县| 雷山县| 彰化市| 红桥区| 印江| 嘉峪关市| 望城县| 浮山县| 乐昌市| 弥勒县| 肥西县| 共和县| 桐乡市| 武平县| 霍林郭勒市| 扶绥县| 新源县|