2022.5.18

Spring Boot 项目中可以存在多个 application.properties 或 apllication.yml。

Spring Boot 启动时会扫描以下 5 个位置的  application.properties 或 apllication.yml 文件,并将它们作为 Spring boot 的默认配置文件。

  1. file:./config/*/
  2. file:./config/
  3. file:./
  4. classpath:/config/
  5. classpath:/

注:file: 指当前项目根目录;classpath: 指当前项目的类路径,即 resources 目录。

以上所有位置的配置文件都会被加载,且它们优先级依次降低,序号越小优先级越高。其次,位于相同位置的 application.properties 的优先级高于 application.yml。

所有位置的文件都会被加载,高优先级配置会覆盖低优先级配置,形成互补配置,即:

  • 存在相同的配置内容时,高优先级的内容会覆盖低优先级的内容;
  • 存在不同的配置内容时,高优先级和低优先级的配置内容取并集。

示例

创建一个名为 springbootdemo 的 Spring Boot 项目,并在当前项目根目录下、类路径下的 config 目录下、以及类路径下分别创建一个配置文件 application.yml,该项目结构如下图。

Spring Boot
图1:Spring Boot 项目配置文件位置


项目根路径下配置文件 application.yml 配置如下。

  1. #项目更目录下
  2. #上下文路径为 /abc
  3. server:
  4. servlet:
  5. context-path: /abc


项目类路径下 config 目录下配置文件 application.yml 配置如下。

  1. #类路径下的 config 目录下
  2. #端口号为8084
  3. #上下文路径为 /helloWorld
  4. server:
  5. port: 8084
  6. servlet:
  7. context-path: /helloworld


项目类路径下的 application.yml 配置如下。

  1. #默认配置
  2. server:
  3. port: 8080

 
在 net.biancheng.www.controller 包下创建一个名为 MyController 的类,代码如下。

  1. package net.biancheng.www.controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.ResponseBody;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. public class MyController {
  7. @ResponseBody
  8. @RequestMapping("/test")
  9. public String hello() {
  10. return "hello Spring Boot!";
  11. }
  12. }
posted @ 2022-05-18 13:55  小强哥in  阅读(24)  评论(0编辑  收藏  举报