# 2.配置文件详解:Properties和YAML

## 一.配置文件的生效顺序，会对值进行覆盖：

1. @TestPropertySource 注解&#x20;
2. 命令行参数
3. Java系统属性（System.getProperties()）
4. 操作系统环境变量
5. 只有在random.\*里包含的属性会产生一个RandomValuePropertySource
6. 在打包的jar外的应用程序配置文件（application.properties，包含YAML和profile变量）
7. 在打包的jar内的应用程序配置文件（application.properties，包含YAML和profile变量）
8. 在@Configuration类上的@PropertySource注解
9. 默认属性（使用SpringApplication.setDefaultProperties指定）

**1配置最优先，9最低**

## 二．配置随机值

src/main/resources/application.properties文件中加入配置

```
demo.secret=${random.value}
demo.number=${random.int}
demo.bignumber=${random.long}
demo.number.less.than.ten=${random.int(10)}
demo.number.in.range=${random.int[1024,65536]}
```

> 注：出现黄点提示，是要提示配置元数据，可以不配置\
> demo可以为任意自定义字符

读取使用注解：`@Value(value = "${demo.secret}")`，这样就可以在项目中采用注释调用了

在类中加入成员变量,则就可以在类中使用成员变量secret，number了

```java
@Value(value = "${demo.secret}")
    private String secret;

@Value(value = "${demo.number}")
    private String number;
```

加入类方法

```java
@RequestMapping(value = "getRandom")
    public Map<String, Object> get() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("secret", secret);
        map.put("number", number);
        return map;
    }
```

访问：<http://localhost:8080/getRandom>

![](/files/-LfnTKNIz-2sSyfFiMdG)

## 三．属性占位符

当application.properties里的值被使用时，它们会被存在的Environment过滤，所以你能够引用先前定义的值（比如，系统属性）。

src/main/resources/application.properties文件中加入配置

```
demo.name=www.shujuwajue.com
demo.desc=${demo.name} is a domain name
```

在类中加入成员变量,则就可以在类中使用成员变量name,desc了

```java
@Value(value = "${demo.name}")
    private String name;

@Value(value = "${demo.desc}")
    private String desc;
```

加入类方法

```java
@RequestMapping(value = "info")
public Map<String, Object> info() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("name", name);
    map.put("desc", desc);
    return map;
}
```

访问：<http://localhost:8080/info>

![](/files/-LfnTKNUUsNgR2g4WUfM)

## 四．Application属性文件，按优先级排序，位置高的将覆盖位置低的

1. 当前目录下的一个/config子目录
2. 当前目录
3. 一个classpath下的/config包
4. classpath根路径（root）

这个列表是按优先级排序的（列表中位置高的将覆盖位置低的,，**也就是1配置最优先，4最低**）

> classpath的理解可以参考：[spring boot加载资源路径配置和classpath问题解决](http://www.jb51.net/article/137029.htm?&_=1527338678846)

校验一下3和4：

resource目录下创建config目录，并创建application.properties文件

加入`demo.desc=${demo.name} is anewdomain name`

![](/files/-LfnTKNblz4wGEM3Zq_J)

访问测试：<http://localhost:8080/info>

![](/files/-LfnTKNdBnQNnu64edy0)

### 五. 配置应用端口和其他配置的介绍

```
#端口配置：application.properties
server.port=8090
#时间格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#时区设置
spring.jackson.time-zone=Asia/Chongqing
```

> ```
> spring.jackson.date-format=yyyy-MM-dd HH:mm:ss 格式化new Date()的格式
> ```

同样也可以在src/main/resources/application.properties文件中加入配置，也可以根据配置文件的优先级加入相应的配置文件中。

## 六. 使用YAML代替Properties

src/main/resources/下的 application.properties 重命名为 application.yaml

```
#自定义配置
demo:
  secret: ${random.value}
  number: ${random.int}
  name: www.shujuwajue.com
  desc: ${demo.name} is a domain name

#端口
server:
  port: 8090


#spring jsckson
spring:
  jackson:
  date-format: yyyy-MM-dd HH:mm:ss
  time-zone: Asia/Chongqing
```

**注意写法：冒号后要加个空格**

## 资料

[Spring Boot 属性配置和使用](https://blog.csdn.net/isea533/article/details/50281151)

[Spring-Boot 相关的一些配置](https://www.jianshu.com/p/9a789d734151)

[spring boot全部配置参数](https://blog.csdn.net/lisulong1/article/details/78901817)

```java
server.context-path=/admin  //配置访问上下文，访问时候需要localhost/admin/xxxx
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://spring-boot.shujuwajue.com/ji-chu-jiao-cheng/pei-zhi-wen-jian-xiang-jie-ff1a-properties-he-yaml.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
