电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

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

瀏覽:12日期:2023-05-05 16:04:13

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

傳統項目讀取配置方式

讀取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慢慢演變,但是本質原理是一樣的,只是SpringBoot簡化配置,通過注解簡化開發,接下來介紹一些常用注解。

@ImportResource注解

這個注解用來導入Spring的配置文件,是配置文件中的內容注入到配置類中,參數是一個數組,可以注入多個配置文件

代碼演示:

在SpringBoot項目的resources目錄下創建一個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 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>

創建配置類ConfigBean

package com.example.test.config;import lombok.Getter;import lombok.Setter;import lombok.ToString;/** * @author Vincente * @date 2020/07/12-12:29 * @desc 配置類 **/@Setter@Getter@ToStringpublic class ConfigBean { private String dbType; private String driverClassName; private String host; private String userName; private String password;}

添加@ImportResource注解,在SpringBoot項目的啟動類添加

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

測試代碼

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

輸出結果

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

小結 @ImportResource注解可以用來加載一個外部xml文件,注入到項目完成配置,但是這樣引入xml并沒有達到SpringBoot簡化配置的目的。

@Configuration和@Bean注解#

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

@Configuration用來代替xml文件,添加在一個類上面

@Bean用來代替bean標簽,聲明在方法上,方法的返回值返回一個對象到Spring的IoC容器中,方法名稱相當于bean標簽中的ID

代碼樣例

聲明一個bean

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

測試代碼

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

輸出結果

com.example.test.config.RestTemplateConfig@de7e193

@Import注解

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

代碼樣例

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

將RestTemplateConfigestTemplateConfig類中的@Configuration注解去掉,在ConfigBean中導入

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

測試代碼

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

輸出結果

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

小結 可以看到在IoC容器中已經導入了RestTemplateConfig(普通)類,這個注解類似于之前applicationContext.xml中的import標簽

@ConfigurationProperties和@Value#

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

代碼樣例

創建配置文件application.yml

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

創建配置類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 配置類 **/@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;}

測試代碼

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

輸出結果

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

-總結 二者的一些區別

特性 @ConfigurationProperties @Value SpEL表達式 不支持 支持 屬性松散綁定 支持 不支持 JSR303數據校驗 支持 不支持

添加校驗注解

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 配置類 **/@Setter@Getter@ToString@ConfigurationProperties(prefix = 'db-config')@Validatedpublic class ConfigBean { @Null private String dbType; private String driverClassName; private String host; private String userName; private String password;}

輸出結果

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這兩個注解默認從項目的主配置文件中讀取配置,當項目配置較多全部從一個地方讀取會顯得臃腫,可以將配置文件按照模塊拆分讀取到不同的配置類中,可以使用@PropertySource配合@Value讀取其他配置文件

代碼樣例

創建配置文件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

創建配置類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 配置類 **/@Setter@Getter@ToString@PropertySource('classpath:db-config.yml')@Componentpublic 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;}

測試代碼

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

輸出結果

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

小結

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

總結

SpringBoot中提供了注解代替配置文件的方式來獲取項目中的配置,大大簡化了開發,以上總結了常用的讀取配置的方法,簡單來說就是兩種文件(yml和properties)幾大注解(@Value,@PropertySource,@Configuration,@ConfigurationProperties,@Import,@Bean);首先要了解每個注解的使用場景后,其次根據項目實際情況來具體的使用

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: SMC-SMC电磁阀-日本SMC气缸-SMC气动元件展示网 | (中山|佛山|江门)环氧地坪漆,停车场地板漆,车库地板漆,聚氨酯地板漆-中山永旺地坪漆厂家 | 钢板仓,大型钢板仓,钢板库,大型钢板库,粉煤灰钢板仓,螺旋钢板仓,螺旋卷板仓,骨料钢板仓 | 视觉检测设备_自动化检测设备_CCD视觉检测机_外观缺陷检测-瑞智光电 | 智能电表|预付费ic卡水电表|nb智能无线远传载波电表-福建百悦信息科技有限公司 | 哈希PC1R1A,哈希CA9300,哈希SC4500-上海鑫嵩实业有限公司 | U拓留学雅思一站式服务中心_留学申请_雅思托福培训 | 东莞螺丝|东莞螺丝厂|东莞不锈钢螺丝|东莞组合螺丝|东莞精密螺丝厂家-东莞利浩五金专业紧固件厂家 | 铝箔袋,铝箔袋厂家,东莞铝箔袋,防静电铝箔袋,防静电屏蔽袋,防静电真空袋,真空袋-东莞铭晋让您的产品与众不同 | 开平机_纵剪机厂家_开平机生产厂家|诚信互赢-泰安瑞烨精工机械制造有限公司 | 罗氏牛血清白蛋白,罗氏己糖激酶-上海嵘崴达实业有限公司 | 金属波纹补偿器厂家_不锈钢膨胀节价格_非金属伸缩节定制-庆达补偿器 | 浴室柜-浴室镜厂家-YINAISI · 意大利设计师品牌 | 咿耐斯 |-浙江台州市丰源卫浴有限公司 | 实验室pH计|电导率仪|溶解氧测定仪|离子浓度计|多参数水质分析仪|pH电极-上海般特仪器有限公司 | 24位ADC|8位MCU-芯易德科技有限公司 | 郑州外墙清洗_郑州玻璃幕墙清洗_郑州开荒保洁-河南三恒清洗服务有限公司 | 电磁辐射仪-电磁辐射检测仪-pm2.5检测仪-多功能射线检测仪-上海何亦仪器仪表有限公司 | 琉璃瓦-琉璃瓦厂家-安徽盛阳新型建材科技有限公司 | 送料机_高速冲床送料机_NC伺服滚轮送料机厂家-东莞市久谐自动化设备有限公司 | 专注提供国外机电设备及配件-工业控制领域一站式服务商-深圳市华联欧国际贸易有限公司 | 电动葫芦|手拉葫芦|环链电动葫芦|微型电动葫芦-北京市凌鹰起重机械有限公司 | 能量回馈_制动单元_电梯节能_能耗制动_深圳市合兴加能科技有限公司 | 螺旋叶片_螺旋叶片成型机_绞龙叶片_莱州源泽机械制造有限公司 | 楼承板设备-楼承板成型机-免浇筑楼承板机器厂家-捡来 | 法兰连接型电磁流量计-蒸汽孔板节流装置流量计-北京凯安达仪器仪表有限公司 | 硬齿面减速机[型号全],ZQ减速机-淄博久增机械 | 天津仓库出租网-天津电商仓库-天津云仓一件代发-【博程云仓】 | 交联度测试仪-湿漏电流测试仪-双85恒温恒湿试验箱-常州市科迈实验仪器有限公司 | 哈希PC1R1A,哈希CA9300,哈希SC4500-上海鑫嵩实业有限公司 | 广东燎了网络科技有限公司官网-网站建设-珠海网络推广-高端营销型外贸网站建设-珠海专业h5建站公司「了了网」 | 环球周刊网| WF2户外三防照明配电箱-BXD8050防爆防腐配电箱-浙江沃川防爆电气有限公司 | 玻璃钢型材_拉挤模具_玻璃钢拉挤设备——滑县康百思 | 深圳货架厂家_金丽声精品货架_广东金丽声展示设备有限公司官网 | 不锈钢复合板厂家_钛钢复合板批发_铜铝复合板供应-威海泓方金属复合材料股份有限公司 | 喷砂机厂家_自动喷砂机生产_新瑞自动化喷砂除锈设备 | 干粉砂浆设备_干混砂浆生产线_腻子粉加工设备_石膏抹灰砂浆生产成套设备厂家_干粉混合设备_砂子烘干机--郑州铭将机械设备有限公司 | 国际线缆连接网 - 连接器_线缆线束加工行业门户网站 | 磁力抛光研磨机_超声波清洗机厂家_去毛刺设备-中锐达数控 | 杭州中策电线|中策电缆|中策电线|杭州中策电缆|杭州中策电缆永通集团有限公司 | vr安全体验馆|交通安全|工地安全|禁毒|消防|安全教育体验馆|安全体验教室-贝森德(深圳)科技 |