> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/24.-externalized-configuration/24.3.-application-property-files.md).

# 24.3. 应用属性文件

`SpringApplication`从以下位置加载`application.properties`文件，并把它们添加到Spring `Environment`中：

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

该列表是按优先级排序的（列表中位置高的路径下定义的属性将覆盖位置低的）。

**注** 你可以使用[YAML（'.yml'）文件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-yaml)替代'.properties'。

如果不喜欢将`application.properties`作为配置文件名，你可以通过指定`spring.config.name`环境属性来切换其它的文件名，也可以使用`spring.config.location`环境属性引用一个明确的路径（目录位置或文件路径列表以逗号分割）。下面的例子展示了怎么指定一个不同的文件名：

```
$ java -jar myproject.jar --spring.config.name=myproject
```

下面的例子展示了怎么指定两个路径：

```
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
```

**注** 在初期需要根据`spring.config.name`和`spring.config.location`决定加载哪个文件，所以它们必须定义为环境属性（通常为OS环境变量，系统属性或命令行参数）。

如果`spring.config.location`包含目录（相对于文件），那它们应该以`/`结尾（运行时，`spring.config.name`关联的名称会在被加载前被追加到后面，包括profile-specific的文件名）。`spring.config.location`下定义的文件使用方法跟往常一样，没有profile-specific变量支持的属性，会被profile-specific的属性覆盖。

配置位置按相反的顺序搜索。默认地，配置好的位置是`classpath:/,classpath:/config/,file:./,file:./config/`。产生的搜索顺序为：

1. `file:./config/`
2. `file:./`
3. `classpath:/config/`
4. `classpath:/`

当使用`spring.config.location`配置好自定义的配置位置时，它们会代替默认位置。比如，如果用值`classpath:/custom-config/,file:./custom-config/`配置了`spring.config.location`，搜索顺序会变成：

1. `file:./custom-config/`
2. `classpath:custom-config/`

或者，当使用`spring.config.additional-location`配置好自定义的配置位置时，，它们会在默认位置的基础上被使用。自定义的位置会在默认位置之前被搜索。例如，如果配置了自定义的位置`classpath:/custom-config/,file:./custom-config/`，搜索的顺序会变成：

1. `file:./custom-config/`
2. `classpath:custom-config/`
3. `file:./config/`
4. `file:./`
5. `classpath:/config/`
6. `classpath:/`

这种搜索排序允许你在一个配置文件里指定默认值，然后有选择地覆盖那些值。你可以选择默认位置中的一处，在这儿的`application.properties`（或者任何由`spring.config.name`指定的名字）里为应用设置默认值。然后，在运行时使用在自定义的位置上的不同的文件，覆盖这些默认值。

**注** 如果使用环境变量而不是系统属性，需要注意多数操作系统的key名称不允许以句号分割（period-separated），但你可以使用下划线（underscores）代替（比如，使用`SPRING_CONFIG_NAME`代替`spring.config.name`）。

**注** 如果你的应用运行在容器中，那么JNDI属性（java:comp/env）或servlet上下文初始化参数可以用来代替环境变量或系统属性，当然也可以使用环境变量或系统属性。
