SpringBoot解析yml/yaml/properties配置文件的四种方式汇总
目录
一、配置文件注入方式一@Value
二、配置文件注入方式二@ConfigurationProperties
三、自定义解析类,直接暴力读取yml配置文件
四、Spring配置文件的解析类Environment获取式
一、配置文件注入方式一@Value
配置文件:
# 严格识别空格# 属性(String/Byte/Short/Integer/Long/Float/Double/Character/Boolean)
properties:name1: 徐城和# 数组/集合(Arrays/List/Set)
arrays:srr1: 小徐,小杨srr2: [小张,小林]# 键值对(Map)
maps:map1: {key1: value1,key2: value2}
注入/解析类:
package parseconfiguration;import autowired.SubGenericityApplication;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;import java.util.Set;/*** 配置文件注入方式一@Value* * 其中,该注入方式:* -仅可注入单属性值和常规数组/集合写法,其它配置或写法需要使用方式二注入* -属性不需要Get/Set方法支持* -可以注入任意类型数据,自动转换注入* -没配置或无法识别或类型无法转换,均会导致配置失败,会报错,因此需要配合default默认值使用* * @author Chenghe Xu* @date 2023/2/14 10:34*/
@SpringBootTest(classes = SubGenericityApplication.class)
public class Test01 {@Value("${properties.name1}")private String name1;@Value("${arrays.srr1}")
// private String[] srr1;
// private List<String> srr1;private Set<String> srr1;@Testpublic void test1() {System.out.println("name1 = " + name1);System.out.print("srr1 = |");for (String s : srr1) {System.out.print(s + "|");}System.out.println();}}/*** 数组注入时会按英文逗号分割* 字符串不会*/
@SpringBootTest(classes = SubGenericityApplication.class)
class Test01_1 {/*** 在生产环境,@Value防止没配置或注入失败,直接报错,需要配合default使用*/@Value("${properties.name2:没配置,没默认值会直接报错}")private String name2;@Value("${arrays.srr2:无法识别,没默认值会直接报错}")
// private String[] srr2;
// private List<String> srr2;private Set<String> srr2;@Value("${maps.map1:类型无法转换,没默认值会直接报错}")private String map1;@Testpublic void test1() {System.out.println("name2 = " + name2);System.out.print("srr2 = |");for (String s : srr2) {System.out.print(s + "|");}System.out.println();System.out.println("map1 = " + map1);}}
二、配置文件注入方式二@ConfigurationProperties
配置文件:
# 严格识别空格
myproperties:# 属性(String/Byte/Short/Integer/Long/Float/Double/Character/Boolean)name1: 徐城和# 数组/集合(Arrays/List/Set)srr1: 小徐,小杨srr2: [小张,小林]srr3:- 小君- 小白# 键值对(Map)map1: {key1: value1,key2: value2}map2:key3: value3key4: value4# 对象(Object)pet1: {name: 旺财,age: 3}pet2: name: 莉莉age: 2
注入/解析类:
package parseconfiguration;import autowired.SubGenericityApplication;
import lombok.Data;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;/*** 配置文件注入方式二@ConfigurationProperties* * 其中,该注入方式:* -需要配合启动类注解标记:@EnableConfigurationProperties({Test02.class})/@ConfigurationPropertiesScan({"parseconfiguration"})* -或配合注册为Bean:@Configuration/@Component,或再引入配置处理器依赖:spring-boot-configuration-processor* -属性需要Get/Set方法支持* -可以注入任意类型数据,自动转换注入* -无法识别或类型无法转换,会导致配置失败,会报错;没配置则不注入* * @author Chenghe Xu* @date 2023/2/17 9:47*/
@Data
//@Component
//@Configuration
@ConfigurationProperties("myproperties")
@SpringBootTest(classes = SubGenericityApplication.class)
public class Test02 {private String name1;// private String[] srr1;
// private String[] srr2;
// private String[] srr3;
// private List<String> srr1;
// private List<String> srr2;
// private List<String> srr3;private Set<String> srr1;private Set<String> srr2;private Set<String> srr3;private Map<String, String> map1;private Map<String, String> map2;private Pet pet1;private Pet pet2;@Testpublic void test1() {System.out.println("name1 = " + name1);System.out.print("srr1 = |");for (String s : srr1) {System.out.print(s + "|");}System.out.println();System.out.print("srr2 = |");for (String s : srr2) {System.out.print(s + "|");}System.out.println();System.out.print("srr3 = |");for (String s : srr3) {System.out.print(s + "|");}System.out.println();System.out.print("map1 = |");map1.forEach((k, v) -> {System.out.print(k + "=");System.out.print(v + "|");});System.out.println();System.out.print("map2 = |");map2.forEach((k, v) -> {System.out.print(k + "=");System.out.print(v + "|");});System.out.println();System.out.println("pet1 = " + pet1);System.out.println("pet2 = " + pet2);}}@SpringBootTest(classes = SubGenericityApplication.class)
class Test02_1 {@Autowiredprivate Test02 test02;@Testpublic void test1() {System.out.println("test02.getName1() = " + test02.getName1());System.out.println("test02.getSrr1() = " + test02.getSrr1());System.out.println("test02.getSrr2() = " + test02.getSrr2());System.out.println("test02.getSrr3() = " + test02.getSrr3());System.out.println("test02.getMap1() = " + test02.getMap1());System.out.println("test02.getMap2() = " + test02.getMap2());System.out.println("test02.getPet1() = " + test02.getPet1());System.out.println("test02.getPet2() = " + test02.getPet2());}}/*** @PostConstruct* 实现全局静态变量访问优化* -可以优化重复的@Autowired注解,直接静态访问*/
@Component
class ConfigurationUtil {public static Test02 staticTest02;@Autowiredpublic Test02 test02;@PostConstructpublic void initialize() {System.out.println("==Spring容器启动时初始化该方法==");staticTest02 = this.test02;}}@SpringBootTest(classes = SubGenericityApplication.class)
class Test02_2 {@Testpublic void test1() {System.out.println("ConfigurationUtil.staticTest02.getName1() = " + ConfigurationUtil.staticTest02.getName1());System.out.println("ConfigurationUtil.staticTest02.getSrr1() = " + ConfigurationUtil.staticTest02.getSrr1());System.out.println("ConfigurationUtil.staticTest02.getSrr2() = " + ConfigurationUtil.staticTest02.getSrr2());System.out.println("ConfigurationUtil.staticTest02.getSrr3() = " + ConfigurationUtil.staticTest02.getSrr3());System.out.println("ConfigurationUtil.staticTest02.getMap1() = " + ConfigurationUtil.staticTest02.getMap1());System.out.println("ConfigurationUtil.staticTest02.getMap2() = " + ConfigurationUtil.staticTest02.getMap2());System.out.println("ConfigurationUtil.staticTest02.getPet1() = " + ConfigurationUtil.staticTest02.getPet1());System.out.println("ConfigurationUtil.staticTest02.getPet2() = " + ConfigurationUtil.staticTest02.getPet2());}}@Data
class Pet {private String name;private Integer age;@Overridepublic String toString() {return "|name=" + name + "|age=" + age + '|';}}
三、自定义解析类,直接暴力读取yml配置文件
配置文件:
#####自定义解析类,直接暴力读取yml配置文件###### 属性(String/Byte/Short/Integer/Long/Float/Double/Character/Boolean)
properties.username1=大傻逼# 数组/集合(Arrays/List/Set)
arrys.srr1=1,2,3,4,5
arrys.srr2=1.1,2.2,3.3,4.4,5.5# 键值对(Map)
maps.map1.key1=vlaue1# 对象(Object)
pets.pet1.name=小汪
pets.pet1.age=1
注入/解析类:
package parseconfiguration;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;/*** 自定义解析类,直接暴力读取yml配置文件** @author Chenghe Xu* @date 2023/2/17 15:48*/
public class Test05 {public static void main(String[] args) {
// Properties properties = ConfigurationReader.properties;Properties properties = ConfigurationReader.getProperties();System.out.print("properties = |");properties.forEach((k, v) -> {System.out.print(k + "=");System.out.print(v + "|");});System.out.println();System.out.println("properties.username1 = " + ConfigurationReader.getProperty("properties.username1"));System.out.println("arrys.srr1 = " + ConfigurationReader.getProperty("arrys.srr1"));System.out.println("arrys.srr2 = " + ConfigurationReader.getProperty("arrys.srr2"));System.out.println("maps.map1.key1 = " + ConfigurationReader.getProperty("maps.map1.key1"));System.out.println("pets.pet1.name = " + ConfigurationReader.getProperty("pets.pet1.name"));System.out.println("pets.pet1.age = " + ConfigurationReader.getProperty("pets.pet1.age"));}}class ConfigurationReader {private static final Logger LOGGER = LoggerFactory.getLogger(Test05.class);// public static Properties properties = new Properties();private static Properties properties = new Properties();public static Properties getProperties() {return properties;}public static String getProperty(String key){return properties.getProperty(key);}/*** static语句块的作用:* 由于static修饰的变量或语句块会在类被加载时,仅且执行一次* 所以可以进行调用方法初始化(静态)成员变量* 即可以通过访问类名访问静态成员变量或其Get方法*/static {init();}public static void init() {InputStream inputStream = null;InputStreamReader inputStreamReader = null;BufferedReader bufferedReader = null;try {// 可解析多个配置文件String[] paths = {"application-Test05.properties"};for (String path : paths) {ClassPathResource resource = new ClassPathResource(path);// 处理中文乱码inputStream = resource.getInputStream();
// inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
// inputStreamReader = new InputStreamReader(inputStream, "utf-8");inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);bufferedReader = new BufferedReader(inputStreamReader);
// properties.load(inputStreamReader);properties.load(bufferedReader);}// 关闭资源inputStream.close();inputStreamReader.close();bufferedReader.close();LOGGER.info("读取完成");} catch (IOException e) {LOGGER.error("无法读取配置文件");}}}
四、Spring配置文件的解析类Environment获取式
配置文件:
#####Spring配置文件的解析类Environment获取式#####
myproperties:es:index:type:documents:fields: 小徐001,小徐002,小徐003
注入/解析类:
package parseconfiguration;import autowired.SubGenericityApplication;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;/*** Spring配置文件的解析类Environment获取式** @author Chenghe Xu* @date 2023/2/21 15:29*/
@SpringBootTest(classes = SubGenericityApplication.class)
public class Test06 {// Spring配置文件的解析类@Autowiredprivate Environment environment;@Testpublic void test1() {// 直接匹配获取String stringArrays01 = environment.getProperty("myproperties.es.index.type.documents.fields");System.out.println("stringArrays01 = " + stringArrays01);// 指定类型获取String[] arrays01 = environment.getProperty("myproperties.es.index.type.documents.fields", String[].class);System.out.print("arrays01 = |");for (String s : arrays01) {System.out.print(s + "|");}System.out.println();// 带默认值获取String stringArrays02 = environment.getProperty("myproperties.es.index.type.documents.fields01", "没有配置该属性");System.out.println("stringArrays02 = " + stringArrays02);// 综合类型和默认值String[] arrays02 = environment.getProperty("myproperties.es.index.type.documents.fields01", String[].class, new String[]{"小徐004","小徐005","小徐006"});System.out.print("arrays02 = |");for (String s : arrays02) {System.out.print(s + "|");}System.out.println();}}
SpringBoot解析yml/yaml/properties配置文件的四种方式汇总相关推荐
- java配置文件实现方式_java相关:详解Spring加载Properties配置文件的四种方式
java相关:详解Spring加载Properties配置文件的四种方式 发布于 2020-4-29| 复制链接 摘记: 一.通过 context:property-placeholder 标签实现配 ...
- java解析与生成json数据的四种方式,比如将json字符串转为json对象或json对象转为json字符串
文章目录 1. 详说json 1.1 何为json 1.2 json语法 2. Java解析与生成JSON的四种方式 2.1 传统方式 2.2 利用Jackson方式 2.3 利用Gson方式 2.4 ...
- Java 读取 .properties 配置文件的几种方式
Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配 ...
- Java中读取properties配置文件的八种方式总结
一.前言 在做Java项目开发过程中,涉及到一些数据库服务连接配置.缓存服务器连接配置等,通常情况下我们会将这些不太变动的配置信息存储在以 .properties 结尾的配置文件中.当对应的服务器地址 ...
- Spring加载properties文件的两种方式
2019独角兽企业重金招聘Python工程师标准>>> 在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取pro ...
- SpringBoot - yml与properties配置文件及bean赋值
SpringBoot - yml与properties配置文件及bean赋值 ① SpringBoot的配置文件 SpringBoot使用一个全局的配置文件,配置文件名是固定的 : applicati ...
- properties类_受不了springboot的yml和properties配置,我扩展出了groovy配置
文中代码地址:https://github.com/gaohanghbut/groovy-configuration 起因 Springboot支持yml和properties两种方式的配置,不知道有 ...
- springboot读取配置文件的三种方式
项目中springboot读取配置文件的三种方式: 1.使用Environment 2.使用@Value 3.使用@ConfigurationProperties注解映射到bean中,定义一个User ...
- php解析url并得到url中的参数及获取url参数的四种方式
本文给大家介绍php解析url并得到url中的参数及获取url参数的四种方式,涉及到将字符串参数变为数组,将参数变为字符串的相关知识,本文代码简单易懂,感兴趣的朋友一起看看吧 下面一段代码是php解析 ...
最新文章
- org.apache.hadoop.fs-ChecksumException
- 并发编程之多线程篇之四
- win server2008搭建ftp服务器
- Keil错误fatal error: UTF-16 (LE) byte order mark detected
- 团队章程---促进团队更合作和更高效
- Duilib教程-HelloDuilib及DuiDesigner的简单使用
- 应该算是在说 delphi 的日志框架吧
- Linux—解压缩命令总结(tar/zip)
- day20 Python 高阶函数,函数,嵌套,闭包 装饰器
- 如何避免程序员的中年危机?
- 鲁大师2014 v3.75.14.1058 官方版
- 华为路由器IPv6 over IPv4 GRE隧道配置详解
- 淘宝京东拼多多自动查券找券返利机器人实现方法分享
- 第三方支付接口有哪些?怎么申请?
- TMS320C5509A 控制DDS AD9854芯片进行AM幅度调制时的FIR滤波处理
- 浦发笔试考计算机知识么,浦发银行考试:笔试到底考什么?
- 2021李林精讲精练880题 【数学二 解析分册】
- 零基础转行学编程技术难吗?
- word指定页插入页码
- 墨珩科技入选工业和信息化重点领域产业人才培训项目评审合格名单