SpringBoot读取自定义配置文件方式(properties,yaml)

目录
  • 一、读取系统配置文件application.yaml
  • 二、读取自定义配置文件properties格式内容
  • 三、读取自定义配置文件yaml格式内容
  • 四、其他扩展内容

一、读取系统配置文件application.yaml

1、application.yaml配置文件中增加一下测试配置

testdata:
  animal:
    lastName: 动物
    age: 18
    boss: true
    birth: 2022/02/22
    maps: {key1:value1,key2:value2}
    list: [dog,cat,house]
    dog:
      name: 旺财
      age: 3

2、新建entity实体类Animal

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component//标识为Bean
@ConfigurationProperties(prefix = "testdata.animal")//prefix前缀需要和yml配置文件里的匹配。
@Data//这个是一个lombok注解,用于生成getter&setter方法
public class Animal {
    private String lastName;
    private int age;
    private boolean boss;
    private Date birth;
    private Map<String,String> maps;
    private List<String> list;
    private Dog dog;
}

3、新建entity实体类dog

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.stereotype.Component;
@Component//标识为Bean
@Data//这个是一个lombok注解,用于生成getter&setter方法
@Configuration//标识是一个配置类
public class Dog {
    private String name;
    private int age;
}

4、新建测试类MyTest

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//让测试运行于Spring测试环境
@SpringBootTest(classes = DemoApplication.class)//指定启动类
@EnableConfigurationProperties(RemoteProperties.class)//使RemoteProperties注解类生效
public class MyTests {
    @Autowired
    Animal animal;
    @Test
    public void test2() {
        System.out.println("person===="+animal);
        System.out.println("age======="+animal.getAge());
        System.out.println("dog.name======="+animal.getDog().getName()+" dog.age===="+animal.getDog().getAge());
    }
}

5、运行结果:

二、读取自定义配置文件properties格式内容

1、resources\config目录下新建remote.properties配置文件,内容如下:

remote.testname=张三
remote.testpass=123456
remote.testvalue=ceshishuju

2、新建entity实体类RemoteProperties

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration//表明这是一个配置类
@ConfigurationProperties(prefix = "remote",ignoreInvalidFields = false)//该注解用于绑定属性。prefix用来选择属性的前缀,也就是在remote.properties文件中的“remote”,ignoreUnknownFields是用来告诉SpringBoot在有属性不能匹配到声明的域时抛出异常。
@PropertySource(value="classpath:config/remote.properties",ignoreResourceNotFound = false)//配置文件路径
@Data//这个是一个lombok注解,用于生成getter&setter方法
@Component//标识为Bean
public class RemoteProperties {
    private String testname;
    private String testpass;
    private String testvalue;
}

3、新建测试类MyTests

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//让测试运行于Spring测试环境
@SpringBootTest(classes = DemoApplication.class)//指定启动类
@EnableConfigurationProperties(RemoteProperties.class)//应用配置文件类,使RemoteProperties注解类生效
public class MyTests {
    @Autowired
    RemoteProperties remoteProperties;
    @Test
    public void test2() {
        TestCase.assertEquals(1, 1);
        String testpass=remoteProperties.getTestpass();
        System.out.println("-----------:"+testpass);
        System.out.println("------------:"+remoteProperties.getTestvalue());
    }
}

4、运行结果:

三、读取自定义配置文件yaml格式内容

1、resources\config目录下新建remote.yaml配置文件,内容如下:

remote:
  person:
    testname: 张三
    testpass: 123456
    testvalue: kkvalue

2、新建工厂转换类PropertySourceFactory

package com.example.demo.db.config;
import org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
//把自定义配置文件.yml的读取方式变成跟application.yml的读取方式一致的 xx.xx.xx
public class MyPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        return new YamlPropertySourceLoader().load(name,encodedResource.getResource()).get(0);
    }
}

3、新建entity实体类RemoteProperties

package com.example.demo.db.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration//表明这是一个配置类
@ConfigurationProperties(prefix = "remote",ignoreInvalidFields = false)//该注解用于绑定属性。prefix用来选择属性的前缀,也就是在remote.properties文件中的“remote”,ignoreUnknownFields是用来告诉SpringBoot在有属性不能匹配到声明的域时抛出异常。
@PropertySource(value="classpath:config/remote.yaml",factory = MyPropertySourceFactory.class)//配置文件路径,配置转换类
@Data//这个是一个lombok注解,用于生成getter&setter方法
@Component//标识为Bean
public class RemoteProperties {
    @Value("${remote.person.testname}")//根据配置文件写全路径
    private String testname;
    @Value("${remote.person.testpass}")
    private String testpass;
    @Value("${remote.person.testvalue}")
    private String testvalue;

}

4、新建测试类MyTests

import com.example.demo.db.config.RemoteProperties;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//让测试运行于Spring测试环境
@SpringBootTest(classes = DemoApplication.class)//指定启动类
@EnableConfigurationProperties(RemoteProperties.class)//使RemoteProperties注解类生效
public class MyTests {
    @Autowired
    RemoteProperties remoteProperties;
    @Test
    public void test2() {
        TestCase.assertEquals(1, 1);
        String testpass=remoteProperties.getTestpass();
        System.out.println("asdfasdf"+testpass);
        System.out.println("asdfasdf"+remoteProperties.getTestvalue());
    }
}

5、运行结果:

说明:

这里需要写一个工厂去读取propertySource(在调试的时候我看到默认读取的方式是xx.xx.xx而自定义的yml配置文件是每一个xx都是分开的,所以不能获取到,而自己创建的配置类MyPropertySourceFactory就是需要把自定义配置文件.yml的读取方式变成跟application的读取方式一致的 xx.xx.xx,并且通过@Value注解指定变量的的关系和yaml配置文件对应)

四、其他扩展内容

可以加入依赖spring-boot-configuration-processor后续写配置文件就有提示信息:

<!-- 导入文件处理器,加上这个,以后编写配置就有提示了-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId> spring-boot-configuration-processor</artifactId>
    <optional> true </optional>
</dependency>

其他获取配置相关内容后续更新。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 在SpringBoot下读取自定义properties配置文件的方法

    SpringBoot工程默认读取application.properties配置文件.如果需要自定义properties文件,如何读取呢? 一.在resource中新建.properties文件 在resource目录下新建一个config文件夹,然后新建一个.properties文件放在该文件夹下.如图remote.properties所示 二.编写配置文件 remote.uploadFilesUrl=/resource/files/ remote.uploadPicUrl=/resource

  • SpringBoot获取yml和properties配置文件的内容

    (一)yml配置文件: pom.xml加入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor --> <dependency> <groupId>org.springframework.boot</groupId>

  • springboot自定义yml配置文件及其外部部署过程

    目录 1.序 2.加载自定义yml文件 2.1.使用@PropertiesSource注解读取yml配置文件-简单版 2.2.使用@PropertiesSource注解读取yml配置文件-不简单版? 2.3.加前缀可行版 3.外部部署 3.1.spring boot核心配置文件外部加载 3.2.在@PropertySource中添加路径 3.3.通过YamlPropertiesFactoryBean添加路径 3.4.自定义yaml文件资源加载类 1.序 背景:有个小项目需要后台,俺顶着Java菜

  • Spring Boot读取自定义配置文件

    @Value 首先,会想到使用@Value注解,该注解只能去解析yaml文件中的简单类型,并绑定到对象属性中去. felord:   phone: 182******32   def:     name: 码农小胖哥     blog: felord.cn     we-chat: MSW_623   dev:     name: 码农小胖哥     blog: felord.cn     we-chat: MSW_623   type: JUEJIN 对于上面的yaml配置,如果我们使用@Va

  • SpringBoot读取外部配置文件的方法

    1.SpringBoot配置文件 SpringBoot使用一个以application命名的配置文件作为默认的全局配置文件.支持properties后缀结尾的配置文件或者以yml/yaml后缀结尾的YAML的文件配置. 以设置应用端口为例 properties文件示例(application.properties): server.port=80 YAML文件示例(application.yml): server: port: 80 在properties和yml/yaml配置文件同时存在的情况

  • SpringBoot读取自定义配置文件方式(properties,yaml)

    目录 一.读取系统配置文件application.yaml 二.读取自定义配置文件properties格式内容 三.读取自定义配置文件yaml格式内容 四.其他扩展内容 一.读取系统配置文件application.yaml 1.application.yaml配置文件中增加一下测试配置 testdata: animal: lastName: 动物 age: 18 boss: true birth: 2022/02/22 maps: {key1:value1,key2:value2} list:

  • springboot读取自定义配置文件节点的方法

    今天和大家分享的是自定义配置信息的读取:近期有写博客这样的计划,分别交叉来写springboot方面和springcloud方面的文章,因为springboot预计的篇章很多,这样cloud的文章就需要等到很后面才能写了:分享这两种文章的原因主要是为了方便自己查找资料使用和对将要使用的朋友起到便捷作用: •@Value标记读取(默认可直接读取application.yml的节点) •实体映射application.yml的节点 •实体映射自定义配置文件的节点 •实体映射多层级节点的值 @Valu

  • springboot读取自定义配置文件时出现乱码解决方案

    目录 网上提供的解决方案也不外乎这几种 方案一 方案二 方案三 方案四 方案五 方案六 这是入门的第三天了,从简单的hello spring开始,已经慢慢接近web的样子.接下来当然是读取简单的对象属性了. 于是按照网上各位大神教的,简单写了个对象book,其他配置不需要做任何改动. package com.example.bean; import org.springframework.beans.factory.annotation.Value; import org.springframe

  • 详解SpringBoot读取resource目录下properties文件的常见方式

    个人理解 在企业开发中,我们经常需要自定义一些全局变量/不可修改变量或者参数来解决大量的变量重复问题,当需要这个全局变量时,只需要从配置文件中读取即可,根据开发中常见的情况,可以分为以下两种情况,分别是: 配置文件为SpringBoot默认的application.properties文件中的自定义参数 加载自定义properties文件中的自定义参数,比如xxx.properties的自定义参数 加载SpringBoot默认的application.properties 准备工作 server

  • springboot读取nacos配置文件的实现

    目录 首先,Nacos 的配置文件如下 第一种方式来解析 第二种方式来解析 SpringBoot 注册服务到 Nacos 上,由 Nacos 来做服务的管理.在 Nacos的配置列表中,管理着服务的配置文件.SpringBoot 有两种方式来读取配置文件的内容,一种是写配置文件类 @ConfigurationProperties ,一种是使用 @Value 注解. 首先,Nacos 的配置文件如下 ### 配置文件使用 yml 格式, 也可以使用 properties 格式,最终 yml 格式会

  • SpringBoot实现自定义配置文件提示的方法

    SpringBoot如何实现自定义配置文件提示 我们在使用SpringBoot开发项目时,常常需要编写一些属性配置类,用来完成自定义或特定的属性配置.在我们配置application.properties时,IDEA会自动提示框架的相关配置,但是我们自己编写的特定的属性配置却不会自动提示.本文介绍了相关的插件,可以实现自定义配置文件的属性提示 1.编写一个配置类 我们编写一个配置类 Person /** * @author zhang_wei * @version 1.0.0 * @Classn

  • Springboot 读取自定义pro文件注入static静态变量方式

    Springboot 读取pro文件注入static静态变量 mailConfig.properties #服务器 mail.host=smtp.qq.com #端口号 mail.port=587 #邮箱账号 mail.userName=hzy_daybreak_lc@foxmail.com #邮箱授权码 mail.passWord=vxbkycyjkceocbdc #时间延迟 mail.timeout=25000 #发送人 mail.emailForm=hzy_daybreak_lc@foxm

  • Springboot 读取 yml 配置文件里的参数值

    目录 方式一 方式二 总结 方式一 1.yml配置 yml配置(示例): api: mes: MES_SOCKET: http://192.168.99.140:8081 2.读取 代码如下(示例): package com.jack.modules.wms.api.common.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; impor

随机推荐