Spring boot 配置文件读取和yaml结构

17 篇文章 4 订阅
8 篇文章 0 订阅

Spring boot 配置文件和ymal结构

源码

源码链接地址:

上一节

Spring boot Banner和icon

yaml

 yaml 简介就不多说了,说白了就是类似json结构,比json更清晰的 kv形式的;通俗易懂。

语法

  1. k: v ; 冒号后面有一个空格
  2. 使用空格缩进,表示层级关系,尽量不要使用tab
  3. 大小写敏感
  4. 驼峰表示, 如:my-name 表示字段myName
  5. '#'表示注释

ymal 中的数据结构

  1. string

普通的value即可。 略

  1. map, object

key, value 形式;
如:
family:
lover: xiaohong
father: xiaoduFather
或者行内表示:
family: {“lover”: “xiaohong”,“father”:“xiaoduFather”}

  1. list

使用 - 表示,或者使用逗号分割;
如:
hobby:
- lol
- ping pong
或者行内表示: hobby: lol,ping pong
也可以带上中括号:hobby: [lol,ping pong]

  1. date

默认格式为 yyyy/MM/dd; 如 birthday: 2010/01/01 12:00:00,或者 2010/01/01

  1. null

使用 ~ 表示; 如:age: ~

  1. 更复杂的对象,可以自行查阅,以上平常开发够用了。

示例

#对象
person:
 # string
  name: xiaodu 
   # null
  age: ~
   #date
  birthday: 200/01/01 12:00:00
  # 集合
  hobby: # 行内表示[lol,ping pong] 
    - lol
    - ping pong
   # map
  family: # 行内表示{"lover": "xiaohong","father":"xiaoduFather"} 
    lover: xiaohong
    father: xiaoduFather

Sprinsg boot 配置文件

根据profiles 读取不同的配置文件

在resources下我们创建4个配置文件, dev 开发; test 测试, prod 生产;
使用 application-{env}.yml 形式命名文件名称

在这里插入图片描述
application.yml
使用spring.profiles.active 指定配置文件

spring:
 profiles:
   active: dev

application-dev.yml, application-test.yml, application-prod.yml 分别指定不同的端口;

#dev
server:
 port: 8081
 #test
 server:
 port: 8082
 #prod
 server:
 port: 8083

当在application.yml中使用spring.profiles.active指定配置文件后,就会加载相应的配置文件信息;有助于我们根据不同的环境切换信息/
也可以在一个配置文件中进行profile的分区; 使用 三个- 进行分区

#application.yml
spring:
 profiles:
   active: test1

---
spring:
 profiles: dev1
server:
 port: 8991
---
spring:
 profiles: test1
server:
 port: 8992
---
spring:
 profiles: prod1
server:
 port: 8993

获取配置信息

配置文件信息

person:
name: xiaodu
age: ~
birthday: 200/01/01 12:00:00
hobby: #[lol,ping pong]
 - lol
 - ping pong
family: #{"lover": "xiaohong","father":"xiaoduFather"}
 lover: xiaohong
 father: xiaoduFather
通过注解获取配置文件信息

@value 获取配置信息
使用 ${key:default} 进行获取配置文件信息; 也可以通过#{} 使用SPEL 表达式进行表示和运算;冒号面跟默认值

   @Value("${person.name:xiaodu}")
   private String name;

   @Value("${person.age}")
   private Integer age;
   
// 使用#{} 进行计算;
//    @Value("#{'${person.hobby}'.split(',')}")
   private String[] hobbys;
   
// 还可以使用dateTimeFormat 进行日期的格式化
//    @DateTimeFormat(pattern = "yyyy-MM-dd")
   @Value("${person.birthday}")
   private Date birthday;

@ConfigurationProperties获取配置信息
推荐使用此方式

直接通过属性映射给配置类信息;配置类必须被spring管理;也就是一个spring bean;
推荐是使用 @EnableConfigurationProperties({UserProperties.class}) 进行; 直接在类上使用@component 也可以。

//prefix 代表前缀
@ConfigurationProperties(prefix = "person")
/*
属性名称相同,直接映射; 大小写,如“ user.my-age  映射  实体属性  myAge
*/
  private String name;
// 接收日期;可以指定格式化; 默认 yyyy/MM/dd
//    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    private List<String> hobby;

    private Integer age;
//  接收map
    private Map<String, String> family;

@PropertySource指定资源位置

   @PropertySource 配合@ConfigurationProperties 进行指定配置文件的位置; 
   @PropertySource 不能使用通配符,只能使用精确的位置; 
   可以使用 classpath, file, url 对资源进行具体的protocol 指定;也可以通过${} 获取配置信息指定的位置
  • classpath
@ConfigurationProperties(prefix = "person1")
@Component
@PropertySource("classpath:user.properties")
  • file
@ConfigurationProperties(prefix = "person1")
@Component
@PropertySource("file:/path/to/file.proerties")
  • url
@Component
@PropertySource("url:${myConfig.url}/config/fruits/price")
@ConfigurationProperties(prefix = "fruits")

url会进行网络请求指定路径获取配置信息;
例如下面模拟了一个接口的返回值,返回的是一个 properties 文件格式的字符串。
通过url指定该路径。

@RestController
@RequestMapping("/config")
public class PropertiesController {

    @GetMapping("/fruits/price")
    public String fruitsPrice() {
        return "fruits.apple=1.2/kg\nfruits.banana=1.5/kg";
    }

}

默认@PropertySource 指定资源位置后,使用properties 后缀的文件信息,若想使用则需要配置yaml解析
使用@propertySource 配置使用yaml
指定yamlpropertysource 的解析; DefaultPropertySourceFactory 是springboot 提供的默认的,只支持kv形式的properties文件格式

  1. 自定义 yamlPropertySourceFactory
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String filename = resource.getResource().getFilename();
        String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        }
        if (filename.endsWith(".yaml") || filename.endsWith(".yml")) {
            YamlPropertiesFactoryBean yamlPropertiesFactoryBean = yamlPropertiesFactoryBean(resource);
            return new PropertiesPropertySource(sourceName, yamlPropertiesFactoryBean.getObject());
        }
        return super.createPropertySource(name, resource);
    }

    public YamlPropertiesFactoryBean yamlPropertiesFactoryBean(EncodedResource encodedResource) {
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        yamlPropertiesFactoryBean.setResources(encodedResource.getResource());
        yamlPropertiesFactoryBean.afterPropertiesSet();
        return yamlPropertiesFactoryBean;
    }
}
  1. @PropertySource 中指定 factory
@ConfigurationProperties(prefix = "person2")
@Component
@PropertySource(value = "classpath:user.yaml", factory = YamlPropertySourceFactory.class)

下一节

Spring boot logging

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值