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

 更新时间:2022年07月08日 10:48:00   作者:zhanhjxxx  
这篇文章主要介绍了SpringBoot读取自定义配置文件方式(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>

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

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

相关文章

  • Java 语言守护线程 Daemon Thread使用示例详解

    Java 语言守护线程 Daemon Thread使用示例详解

    这篇文章主要为大家介绍了Java 语言守护线程 Daemon Thread使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-10-10
  • Java递归 遍历目录的小例子

    Java递归 遍历目录的小例子

    Java递归 遍历目录的小例子,需要的朋友可以参考一下
    2013-03-03
  • Spring Boot集成Kafka的示例代码

    Spring Boot集成Kafka的示例代码

    本篇文章主要介绍了Spring Boot集成Kafka的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • SpringBoot请求参数相关注解说明小结

    SpringBoot请求参数相关注解说明小结

    这篇文章主要介绍了SpringBoot请求参数相关注解说明,主要包括@PathVariable,@RequestHeader、@CookieValue、@RequestBody和@RequestParam,本文结合实例代码给大家讲解的非常详细,需要的朋友可以参考下
    2022-05-05
  • SpringBoot解决ajax跨域问题的方法

    SpringBoot解决ajax跨域问题的方法

    这篇文章主要为大家详细介绍了SpringBoot解决ajax跨域问题的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • Java如何在 Word 中设置上、下标

    Java如何在 Word 中设置上、下标

    这篇文章主要介绍了Java如何在 Word 中设置上、下标,帮助大家更好的利用Java处理文档,感兴趣的朋友可以了解下
    2020-09-09
  • 解析springboot集成AOP实现日志输出的方法

    解析springboot集成AOP实现日志输出的方法

    如果这需要在每一个controller层去写的话代码过于重复,于是就使用AOP定义切面 对其接口调用前后进行拦截日志输出。接下来通过本文给大家介绍springboot集成AOP实现日志输出,需要的朋友可以参考下
    2021-11-11
  • springboot集成Mybatis-plus-join-boot-start详解

    springboot集成Mybatis-plus-join-boot-start详解

    这篇文章主要介绍了springboot集成Mybatis-plus-join-boot-start方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-04-04
  • Java经典算法汇总之选择排序(SelectionSort)

    Java经典算法汇总之选择排序(SelectionSort)

    选择排序也是比较简单的一种排序方法,原理也比较容易理解,选择排序在每次遍历过程中只记录下来最小的一个元素的下标,待全部比较结束之后,将最小的元素与未排序的那部分序列的最前面一个元素交换,这样就降低了交换的次数,提高了排序效率。
    2016-04-04
  • Java如何将时间戳格式化为日期字符串

    Java如何将时间戳格式化为日期字符串

    这篇文章主要介绍了Java如何将时间戳格式化为日期字符串问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04

最新评论