参考资料

  1. SpringBoot读取外部配置文件的方法
  2. Springboot项目jar包读取配置文件的优先级
  3. SpringBoot配置文件加载优先级(全)

一. 前期准备

⏹工程内的配置文件

在这里插入图片描述

⏹配置类,封装配置文件信息

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration("configInfo")
public class SettingConfig {

    @Value("${custom.count}")
    public String count;

    @Value("${custom.info}")
    public String info;
}

⏹前台html,用于展示配置文件中的信息

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <script type="text/javascript" th:src="@{/js/public/jquery-3.6.0.min.js}"></script>
    <script type="text/javascript" th:src="@{/js/common/common.js}"></script>
    <title>test8页面</title>
</head>
<body>
    <h1 id="title"></h1>
    <h2 id="info"></h2>
</body>
<script th:inline="javascript">
    // 后台配置文件中的信息
    const count = [[${@configInfo.count}]];
    const info = [[${@configInfo.info}]];
</script>
<script>
	// 将后台配置信息展示到前台
    $(function () {
        $("#title").text(count);
        $("#info").text(info);
    });
</script>
</html>

⏹将工程打包为jar包,在jar包同级别目录下创建一个config文件夹和一个application.yml配置文件
在这里插入图片描述
application.yml配置文件信息

spring:
  datasource:
    url: jdbc:mysql://localhost/myblog?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
    username: root
    password: mysql
  messages:
    basename: i18n/messages
    encoding: UTF-8

# 自定义配置信息
custom:
  count: 6000

然后在config文件夹中再创建一个application.yml配置文件,详细信息为

spring:
  datasource:
    url: jdbc:mysql://localhost/myblog?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
    username: root
    password: mysql
  messages:
    basename: i18n/messages
    encoding: UTF-8

# 自定义配置信息
custom:
  count: 5000

二. SpringBoot工程读取配置文件具有优先级

优先级由高到低依次为

  • 通过命令行--spring.config.location指定配置文件路径(优先级最高)
  • jar包同级别目录中的config文件夹下的配置文件
  • jar包同级别目录中的配置文件
  • jar包内的配置文件

三. SpringBoot工程读取配置文件具有覆盖性

⏹springboot服务启动时会按优先级搜寻所有的配置文件,而不是搜寻到就停止搜寻了;这意味着:所有配置文件中的属性配置都会被 springboot服务读取并使用到;且当这些配置文件中具有相同属性配置时,优先级高的配置文件中的属性配置会覆盖优先级低的。

⏹当使用--spring.config.location指令用于指定配置文件的时候,指定后jar包就直接使用指定的配置文件;不再搜寻其他的任何配置文件,因此不存在优先级和覆盖原则

  • jar包所在目录中的config文件夹下的配置文件
    # 自定义配置信息
    custom:
      count: 5000
    
  • jar包内部的配置文件
    custom:
      count: 300
      info: info of resources
    
  • 最终SpringBoot使用的配置文件为
    custom:
      count: 5000
      info: info of resources
    
    • 由于custom.info是config文件夹下的配置文件中没有的,因此会使用jar包内部的配置信息;
    • 而custom.count是config文件夹下的配置文件中存在的,因此会覆盖jar包内部的配置信息

四. 优先级效果展示

4.1 若目录下只有jar包

在这里插入图片描述在这里插入图片描述在这里插入图片描述

4.2 若目录下有配置文件,config文件夹下还有配置文件

在这里插入图片描述
在这里插入图片描述
6000来源于config文件夹下的配置文件,而info of resources来源于jar包内部的配置文件
在这里插入图片描述

4.3 若使用–spring.config.location来指定配置文件启动

java -jar jmw-0.0.1-SNAPSHOT.jar --spring.config.location=.\config\application.yml
在这里插入图片描述
因为--spring.config.location这种方式不存在优先级和覆盖原则,因此无法从指定的外部配置文件中读取到custom.info,因此会报错.

如果将指定配置文件改为入下所示之后再启动
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐