Spring Boot中配置文件占位符,Profile多文档块模式和配置文件加载优先级的介绍

一、这篇博客主要介绍Spring Booot中的配置文件占位符使用,在yml配置文件中Profile多文档块模式的介绍和使用,以及介绍配置文件的加载优先级。

二、配置文件占位符

【1】配置文件中可以使用随机数:

  • ${random.value}
  • ${random.int}
  • ${random.long}
  • ${random.int(10)}
  • ${random.int[1024,4201]}

代码下所示:
①、application.yml

test:
  one: ${random.value}
  two: ${random.int}
  three: ${random.long}
  four: ${random.int(10)}
  five: ${random.int[1024,4201]}

②、Number 类

package com.czd.springbootdemo.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @author czd
 */
@Component
@ConfigurationProperties(prefix = "test")
@PropertySource("classpath:application.yml")
public class Number {
    private String one;
    private int two;
    private long three;
    private int four;
    private int five;

    //下面省略Setter和Getter方法以及toString方法
}

③、SpringBootDemoApplicationTests测试类

package com.czd.springbootdemo;

import com.czd.springbootdemo.bean.Number;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDemoApplicationTests {

    @Autowired()
    Number number;
    @Test
    public void testNumber(){
        System.out.println(number);
    }

}

输出结果

Number{one='a0c20a576ec66382551ff989f3ddc117', two=-1341843913, three=-5359733146202224399, four=3, five=2089}

【2】属性配置符

①、application.yml

test:
  one: ${random.value}
  two: 50
  three: ${random.long}
  four: ${random.int(10)}
  five: ${random.int[1024,4201]}
  first: ${test.two}
  second: ${test.no:你好}

②、其他Java类的话和【1】中的一样,这里就不再说了,最后输出结果如下:

Number{one='041c70a596d87b9c2dea250c68ecb4c9', two=50, three=-2973124866270938476, four=3, five=2701, first=50, second='你好'}

三、Profile-多文档块模式介绍
Profile是Spring Boot对不同环境提供不同配置功能的支持,可以通过激活,指定参数等方式快速切换环境,在这里主要介绍在yml配置文件下Profile多文档块模式。

【1】用 - - - 将文档分为5个文档块,其中 spring: profile 是设置文档块环境名字,spring: profile: active是激活指定环境,这里是激活名称为two的文档块的环境,其Tomcat服务器端口号是代码如下所示:

server:
  port: 8081
spring:
  profiles:
    active: three
---
server:
  port: 8082
spring:
  profiles: one
---
server:
  port: 8083

spring:
  profiles: two
---
server:
  port: 8084
spring:
  profiles: three
---

输出结果
在这里插入图片描述
可以看到Tomcat的端口号是8084,说明修改成功。

四、配置文件的加载优先级
Spring Boot启动会扫描以下位置的application.properties或者application.yml作为Spring Boot的默认文件,优先级如下所示 ① 到 ④ 代表优先级由高到低。
- file: ./config
- file: ./
- classpath: ./config
- classpath: ./

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值