一、读取系统配置文件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>

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

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

SpringBoot读取自定义配置文件方式(properties,yaml)的更多相关文章

  1. xcode – osx上的config.log是什么?它在哪里?

    任何人都可以解释’configure’是什么和做什么,一般可以找到config.log文件?

  2. 在swift中获取NSImage的PNG表示

    非常感谢文件说:所以它期望一本字典,而不是一个零值.提供像这样的空字典:只有在指定了Optional(即[NSObject:AnyObject]的位置?)时才能传递nil值.

  3. android – Eclipse:覆盖project.properties中定义的库路径

    我正在使用ActionBarSherlock作为库.我们没有将ABS包含在我们的存储库中,因此参与ourproject的每个人都必须单独下载并安装它.ActioBarSherlock是一个Android库项目,我通过在同一个Eclipse的工作区中打开它和我的项目来运行它(它们都没有复制到工作区,它们都存在于另一个文件夹中)并通过以下方式将它添加到我的project.properties中:Ref

  4. android – Crashlytics无法使用fabric.properties找到清单

    我正在使用classpath’io.fabric.tools:gradle:1.‘并且在我用于fabric插件的模块中有一个fabric.properties.当我运行gradlewcrashlyticsuploaddistributionProdStaging时,我得到:为什么?解决方法在我使用正确的数据更新fabric.properties并拆分命令后,它工作正常:没有它,错误仍然出现.

  5. 缺少android.compileSdkVersion!错误gradle build

    我正在尝试构建我的库并将其上传到存储库,但不幸的是gradle构建失败.我花了几个小时试图修复这个错误,但我尝试的没有任何帮助.这是我从根项目目录的build.gradle.和我的模块目录中的build.gradle我还在local.properties文件中添加了一些配置问题是我在gradlebintrayUpload之后遇到以下错误.在错误消息输出结束时,我得到了以下内容解决方法与“编译sdk

  6. android – Gitignore没有忽略某些project.properties

    我正在使用Windows和Mac的github应用程序,我的.gitignore文件有问题.我试图忽略在我的两台机器之间切换时生成的project.properties文件,但我似乎无法让它工作.下面是我的.gitignore的副本,它似乎适用于除了project.properties之外的所有东西,以及我在那里的gen/*,但不那么烦人.我一直在研究这个问题并且没有找到答案,我将不胜感激任何帮助!

  7. SpringBoot本地磁盘映射问题

    这篇文章主要介绍了SpringBoot本地磁盘映射问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  8. java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源)

    这篇文章主要介绍了java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源),文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

  9. SpringBoot整合Javamail实现邮件发送的详细过程

    日常开发过程中,我们经常需要使用到邮件发送任务,比方说验证码的发送、日常信息的通知等,下面这篇文章主要给大家介绍了关于SpringBoot整合Javamail实现邮件发送的详细过程,需要的朋友可以参考下

  10. SpringBoot详细讲解视图整合引擎thymeleaf

    这篇文章主要分享了Spring Boot整合使用Thymeleaf,Thymeleaf是新一代的Java模板引擎,类似于Velocity、FreeMarker等传统引擎,关于其更多相关内容,需要的小伙伴可以参考一下

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部