学透Spring Boot — 007. 加载外部配置

Spring Boot会从多个目录下查找并加载配置。我们今天来学习这几种加载外部应用配置的方式。

默认目录 classpath

Spring Boot 默认会从 classpath 下加载application.properties或者application.yaml配置。这也是大部分项目默认使用的方式。

项目中最常用的也是默认的classpath是src/main/resources/

properties 复制代码
server.port=9001
默认目录 classpath下的config目录

在classpath下的config目录的配置,也会被Spring Boot 默认加载。

根目录下的config目录

项目根目录下的config目录的配置也会被默认加载,而且优先级比classpath下的更高。

修改默认加载目录 spring.config.location

有时候我们不想从classpath中加载,而是一个自定义的目录作为我们的配置目录,这时候 spring.config.location 这个配置项就起作用了。

我们可以在环境变量、系统变量或者命令行参数中使用这个配置项。

这样,Spring Boot就把项目根目录下的abc-test目录下的application.properties作为我们的配置。

特别注意的是,我们使用了这种配置后,src/main/resources这种classpath下的配置就失效了,Spring Boot不会去加载。

或者我们可以指定某个目录

复制代码
-Dspring.config.location=file:./abc-test/

像前面,我们可以根据文件相对路径和绝对路径file:./abc-test

我们也可以指定classpath下的某个folder

复制代码
-Dspring.config.location=classpath:custom-config/

不管配置file:./XXX 或者 classpath:XXX,如果XXX 目录不存在,应用启动会失败。

要解决这个问题,我们可以加上optional的选项。

加载额外配置 additional-location

前面说过 spring.config.location 会导致src/main/resources这个配置路径失效,这通常是我们不期望的。怎么保留src/main/resources的前提下,加载其它folder的配置呢?

这时候,我们可以使用spring.config.additional-location 这个配置项。

导入额外的配置 import

类似 spring.config.location 配置,我们还有一种方法,在保留加载classpath的前提下,还能加载外部配置。

src/main/resources/application.properties

复制代码
spring.config.import=file:./abc-test/

或者指定具体的配置文件

复制代码
spring.config.import=file:./abc-test/hello.properties

也可以是一个yaml格式的配置

复制代码
spring.config.import=file:./abc-test/hello.yaml

hello.yaml

复制代码
server:
  port: 9008
加载json作为配置

如果某些场景,我们需要加载一个json文件作为我们的应用配置,Spring Boot支持这种配置方式吗?

让我们来试试

然后我们来试试使用import的方式

src/main/resources/application.properties

复制代码
spring.config.import=file:./abc-test/hello.json

非常可惜的是,启动应用报错:

Unable to load config data from 'file:./abc-test/hello.json'

File extension is not known to any PropertySourceLoader. If the location is meant to reference a directory, it must end in '/' or File.separator

查看Spring Boot的源码可以知道,原来Spring boot的import只支持两种文件后缀

  • properties
  • yaml

还支持目录.

复制代码
spring.config.import=file:./abc-test/

这样能加载abc-test目录下的hello.json配置吗?很可惜,不支持。

后来我想当一种walkaround,把app.json的后缀改一下可以吗?

居然可以!!!!

根本原因

Json is subset of yaml

Json 是 Yaml的子集。

相关推荐
thefool11226610 分钟前
Java 面向对象
java
2501_9481069112 分钟前
计算机毕业设计之jsp-智慧旅游分享平台
java·开发语言·spark·汽车·课程设计·旅游
茶栀(*´I`*)15 分钟前
Android 测试入门指南:ADB 基础配置与常用设备管理命令解析
android·adb
阿里云云原生31 分钟前
Agent 不再是“玩具”!AgentScope Java 2.0 GA 发布:构建企业级分布式智能体底座
java·开发语言·分布式·agentscope
41541131 分钟前
MyBatis-Plus + PostGIS 实战(四):GeoJSON 序列化与前端地图对接,全局 WKT + 局部 GeoJSON,两种格式优雅共存
java·mybatis·postgis·geojson
峥嵘life1 小时前
Andorid 打开热点,关闭有线网,ifconfig卡死分析解决
java·服务器·网络
HillVue1 小时前
Token 叙事退潮,DAA 重新定义 AI 价值标准
java·人工智能·eclipse
行者全栈架构师1 小时前
【码动四季】Spring Boot 可观测性体系:Micrometer + OpenTelemetry + Grafana 全链路搭建
java·算法·架构
TDengine (老段)1 小时前
TDengine JOIN 完整语法 — Inner/Outer/ASOF/Window 全语法详解
java·大数据·数据库·物联网·时序数据库·tdengine·涛思数据
@灯神2 小时前
SpringAI系列|第1篇:SpringAI概述与快速上手
java·人工智能·spring·ai·ai编程