SpringBoot之外部化配置

news2024/9/21 12:26:47

前言

SpringBoot 版本 2.6.13,相关链接 Core Features

  1. Default properties (specified by setting SpringApplication.setDefaultProperties).
  2. @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.
  3. Config data (such as application.properties files).
  4. A RandomValuePropertySource that has properties only in random.*.
  5. OS environment variables.
  6. Java System properties (System.getProperties()).
  7. JNDI attributes from java:comp/env.
  8. ServletContext init parameters.
  9. ServletConfig init parameters.
  10. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
  11. Command line arguments.
  12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
  13. @TestPropertySource annotations on your tests.
  14. Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.

Default properties

默认情况下的启动类

@SpringBootApplication
public class BlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

添加 defaultProperties

@SpringBootApplication
@Slf4j
public class BlogApplication {

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("hello", "world");

        SpringApplication springApplication = new SpringApplication(BlogApplication.class);
        springApplication.setDefaultProperties(map);
        ConfigurableApplicationContext context = springApplication.run(args);
        String property = context.getEnvironment().getProperty("hello");
        log.info(property);
    }
}

启动项目,查看运行结果

@PropertySource

创建 key.properties

name=Anna
运行 Main 方法,查看运行结果
@Slf4j
@SpringBootApplication
@PropertySource("classpath:key.properties")
public class BlogApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BlogApplication.class, args);
        String property = context.getEnvironment().getProperty("name");
        log.info(property);
    }
}

Config data

默认配置文件位置(ConfigDataEnvironment#DEFAULT_SEARCH_LOCATIONS)

  • optional:classpath:/
  • optional:classpath:/config/
  • optional:file:./
  • optional:file:./config/
  • optional:file:./config/*/

默认配置文件前缀(StandardConfigDataLocationResolver#DEFAULT_CONFIG_NAMES)

  • application

默认配置文件后缀(YamlPropertySourceLoader & PropertiesPropertySourceLoader)

  • yml
  • yaml
  • properties
  • xml

所以默认情况下,以下文件(文件在指定位置)都可以认为是配置文件:

  • application.yml
  • application.yaml
  • application.properties
  • application.xml

前三个文件我们经常遇到,主要演示一下第四个配置文件

演示 application.xml

创建 application.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

<properties>
  <entry key="config.xml.name">application.xml</entry>
</properties>
运行 Main 方法,查看运行结果
@Slf4j
@SpringBootApplication
@PropertySource("classpath:key.properties")
public class BlogApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BlogApplication.class, args);
        String property = context.getEnvironment().getProperty("config.xml.name");
        log.info(property);
    }
}

分隔符 ---

如果配置文件里面存在分隔符 --- ,则可以将文件看出多个配置文件,分隔符下方的配置优先级更高

server:
  port: 8080
---
server:
  port: 8081

spring.config.location

覆盖默认配置文件位置

在 idea 中添加参数 --spring.config.location=classpath:/custom/

或者在启动类添加参数 --spring.config.location=classpath:/custom/

创建文件夹 custom,并创建文件 application.yaml,明细如下:
prop:
  sign:
    custom: custom-application-yaml
运行 Main 方法,查看运行结果
@Slf4j
@SpringBootApplication
@PropertySource("classpath:key.properties")
public class BlogApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BlogApplication.class, "--spring.config.location=classpath:/custom/");
        String property = context.getEnvironment().getProperty("prop.sign.custom");
        log.info(property);
    }
}

  • tomcat启动端口8080:在上文中默认配置文件配置的 server.port = 8081,所以默认配置未加载
  • 属性 prop.sign 不为 null:自定义文件夹下的配置文件生效

spring.config.additional-location

配置附加位置

在 idea 中添加参数 --spring.config.location=classpath:/custom/ --spring.config.additional-location=classpath:/additional/

创建文件夹 additional,并创建文件 application.yaml,明细如下:
prop:
  sign:
    additional: additional-application-yaml
运行 Main 方法,查看运行结果
@Slf4j
@SpringBootApplication
@PropertySource("classpath:key.properties")
public class BlogApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BlogApplication.class, args);
        String property1 = context.getEnvironment().getProperty("prop.sign.custom");
        String property2 = context.getEnvironment().getProperty("prop.sign.additional");
        log.info(property1);
        log.info(property2);
    }
}

spring.config.import

1.在配置文件中配置
修改 application.yaml
server:
  port: 8080

spring:
  config:
    import: classpath:import/a.yaml
创建文件夹 import,并创建文件 a.yaml、b.yaml、c.yaml,明细如下:
a.yaml
server:
  port: 8082

spring:
  config:
    import: classpath:import/b.yaml
 b.yaml
server:
  port: 8083

spring:
  config:
    import: classpath:import/c.yaml
 c.yaml
server:
  port: 8084
运行 Main 方法,查看运行结果
@Slf4j
@SpringBootApplication
@PropertySource("classpath:key.properties")
public class BlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

2.在 idea 中添加参数 --spring.config.import=classpath:import/a.yaml
 修改 application.yaml
server:
  port: 8080
添加参数

运行 Main 方法,查看运行结果
@Slf4j
@SpringBootApplication
@PropertySource("classpath:key.properties")
public class BlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

spring.profiles.active

SpringBoot 的解析分为两个阶段(BEFORE_PROFILE_ACTIVATION & AFTER_PROFILE_ACTIVATION),spring.config.location、spring.config.additional-location、spring.config.import 的解析阶段是 BEFORE_PROFILE_ACTIVATION,spring.profiles.active 的解析阶段是 AFTER_PROFILE_ACTIVATION ,与其相关的的配置如下:

  • spring.profiles.default
  • spring.profiles.include
  • spring.profiles.group
  • spring.config.activate.on-profile
spring.profiles.default

默认值为 default,如果 spring.config.location、spring.config.additional-location、spring.config.import 解析出来的配置文件里面没有配置 spring.profiles.active、spring.profiles.include,则默认激活 application-default.yaml (yml | properties | xml) 

spring.profiles.active

会激活配置文件  application-{profiles}.yaml (yml | properties | xml) 

spring.profiles.include

spring.profiles.active 的集合形式,用逗号分割

spring.profiles.group

如果 spring.profiles.active、spring.profiles.include 指定的值中与 spring.profiles.group 的某个组名一致,则激活组名及组内元素对应的配置。比如以下配置,则会激活 g1、e1、e2

spring:
  profiles:
    active: g1
    group:
      g1:
        - e1
        - e2
      g2:
        - e3
        - e4
spring.config.activate.on-profile

spring.config.location、spring.config.additional-location、spring.config.import 解析出来的配置文件,只有在某个配置文件激活的状态下才生效

PS :待激活的配置文件  application-{profiles}.yaml (yml | properties | xml)  里不可存在以下配置:

  • spring.profiles.include
  • spring.profiles.include[0]
  • spring.profiles.active
  • spring.profiles.active[0]
  • spring.profiles.default
  • spring.profiles.default[0]

Configuring Random Values

  • ${random.value}:加密数据
  • ${random.int}:随机数(int)
  • ${random.long}:随机数(long)
  • ${random.uuid}:uuid
  • ${random.int(10)}:[ 0,10)
  • ${random.int[1024,65536]}:[ 1024,65536)
@EnableConfigurationProperties + @ConfigurationProperties 使用案例
配置文件
my:
  secret: ${random.value}
  number: ${random.int}
  bignumber: ${random.long}
  uuid: ${random.uuid}
  number-less-than-ten: ${random.int(10)}
  number-in-range: ${random.int[1024,65536]}
创建实体类 RandomEntity
@Data
@ConfigurationProperties(prefix = "my")
public class RandomEntity {

    private String secret;

    private Integer number;

    private Long bignumber;

    private String uuid;

    private String numberLessThanTen;

    private Integer numberInRange;

    @Override
    public String toString() {
        return "RandomEntity{" +
                "secret='" + secret + '\'' +
                ", number=" + number +
                ", bignumber=" + bignumber +
                ", uuid='" + uuid + '\'' +
                ", numberLessThanTen='" + numberLessThanTen + '\'' +
                ", numberInRange=" + numberInRange +
                '}';
    }
}
运行 Main 方法,查看运行结果
@Slf4j
@SpringBootApplication
@EnableConfigurationProperties(RandomEntity.class)
public class BlogApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BlogApplication.class, args);
        RandomEntity randomEntity = context.getBean(RandomEntity.class);
        System.out.println(randomEntity);
    }
}

System properties & System environment

可以获取系统属性以及系统环境变量

使用案例
@Slf4j
@SpringBootApplication
@EnableConfigurationProperties(RandomEntity.class)
public class BlogApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BlogApplication.class, args);
        ConfigurableEnvironment environment = context.getEnvironment();
        String javaRuntimeName = environment.getProperty("java.runtime.name");
        String javaHome = environment.getProperty("JAVA_HOME");
        System.out.println(javaRuntimeName);
        System.out.println(javaHome);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1983459.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何在群晖NAS中搭建影音管理利器nastool并实现远程访问本地资源

文章目录 前言1. 本地搭建Nastool2. nastool基础设置3. 群晖NAS安装内网穿透工具4. 配置公网地址5. 配置固定公网地址 前言 Nastool是为群晖NAS玩家量身打造的一款智能化影音管理利器。它不仅能够满足电影发烧友、音乐爱好者和追剧达人的需求&#xff0c;更能让你在繁忙的生活…

疯狂的马达——Arduino

本次学习目标 1、了解马达的运用、以及马达内部的基本原理。 2、学会通过编程控制马达的速度、方向。 3、制作电位器换挡风扇。 马达 “马达”为英语motor的音译&#xff0c;我们称为电机&#xff0c;电机又可分为 发电机和电动机。前者是一种能够将动能转化电能的装置&am…

【知识】pytorch中的pinned memory和pageable memory

转载请注明出处&#xff1a;小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你&#xff0c;欢迎[点赞、收藏、关注]哦~ 目录 概念简介 pytorch用法 速度测试 反直觉情况 概念简介 默认情况下&#xff0c;主机 &#xff08;CPU&#xff09; 数据分配是可分页的。GPU 无…

计算机系统的基本结构-CSP初赛知识点整理

真题练习 [2021-CSP-J-第3题] 目前主流的计算机储存数据最终都是转换成&#xff08; &#xff09;数据进行储存。 A.二进制 B.十进制 C.八进制 D.十六进制 [2020-CSP-J-第1题] 在内存储器中每个存储单元都被赋予一个唯一的序号&#xff0c;称为( ) A&#xff0e;地址 B&a…

探索 Electron 应用的本地存储:SQLite3 与 Knex.js 的协同工作

electron 简介 Electron 是一个使用 JavaScript, HTML 和 CSS 构建跨平台桌面应用程序的框架。 它允许开发者使用 Web 技术来创建桌面软件&#xff0c;而不需要学习特定于平台的编程语言。 Electron 应用程序实际上是一个包含 Web 内容的 Chromium 浏览器实例&#xff0c;并…

创建型模式(Creational Patterns)之工厂模式(Factory Pattern)之简单工厂模式(Simple Factory Pattern)

1.简单工厂模式&#xff08;Simple Factory Pattern&#xff09;&#xff0c;又叫做静态工厂方法&#xff08;Static FactoryMethod Pattern&#xff09;。 1.1 基本介绍 被创建的对象称为“产品”&#xff0c;创建产品的对象称为“工厂”。如果要创建的产品不多&#xff0c;只…

WPF-实现多语言的静态(需重启)与动态切换(不用重启)

一、多语言切换&#xff08;需重启&#xff09; 1、配置文件添加Key <appSettings><add key"language" value"zh-CN"/></appSettings> 2、新增附加属性当前选择语言 public CultureInfo SelectLanguage{get > (CultureInfo)GetValu…

使用Go语言绘制柱状图教程

使用Go语言绘制柱状图教程 本文将介绍如何使用Go语言及gg包绘制柱状图&#xff0c;并将图表保存为PNG格式的图片。gg包是一个功能强大的2D图形库&#xff0c;适合用于绘制各种图表。 安装gg包 首先&#xff0c;确保你已经安装了gg包。如果还没有安装&#xff0c;可以使用以下…

Java二十三种设计模式-组合模式(11/23)

组合模式&#xff1a;构建层次化结构的灵活方案 引言 组合模式&#xff08;Composite Pattern&#xff09;是一种结构型设计模式&#xff0c;用于将对象组合成树形结构以表示“部分-整体”的层次结构。这种模式使得用户对单个对象和组合对象的使用具有一致性。 基础知识&…

Linux 命令,mkdir说明与使用

1&#xff1a;mkdir命令功用&#xff1a; 用于创建一个或多个目录&#xff0c;创建目录&#xff0c;必须在父目录中写上权限。 新目录的默认模式为0777&#xff0c;可以由系统或用的umask来修改。 2&#xff1a;命令构件: mkdir [options] directories 3:参数选项: -m&#x…

海洋知识竞赛规则流程方案

为贯彻落实“进一步关心海洋、认识海洋、经略海洋”的重要指示精神&#xff0c;引导社会公众学习海洋知识、增强海洋意识、保护海洋环境&#xff0c;推动建设海洋强国&#xff0c;推进人与自然和谐共生的现代化&#xff0c;围绕“保护海洋 人与自然和谐共生”的主题&#xff0c…

机械学习—零基础学习日志(高数22——泰勒公式理解深化)

核心思想&#xff1a;函数逼近 在泰勒的年代&#xff0c;如果想算出e的0.001次方&#xff0c;这是很难计算的。那为了能计算这样的数字&#xff0c;可以尝试逼近的思想。 但是函数又不能所有地方都相等&#xff0c;那退而求其次&#xff0c;只要在一个极小的范围&#xff0c;…

EMQX服务器安装MQTT测试

cd /usr/local/develop wget https://www.emqx.com/en/downloads/broker/5.7.1/emqx-5.7.1-el7-amd64.tar.gz mkdir -p emqx && tar -zxvf emqx-5.7.1-el7-amd64.tar.gz -C emqx ./emqx/bin/emqx start 重启 ./emqx/bin/emqx restart http://10.8.0.1:18083/ 账号ad…

sql第一次

第五关 然后修改userLess-5 Double Query- Single Quotes- Stringhttp://localhost/sql/Less-5/?id1%27%20and%20updatexml(1,concat(0x7e,(select%20group_concat(username,0x3a,password)from%20users),0x7e),1)--substr截取 在前面截取 注意不要少写括号&#xff0c;不然会…

FFmpeg推流

目录 一. 环境准备 二. 安装FFmpeg 三. 给docker主机安装docker服务 四. 使用 FFmpeg 进行推流测试 FFmpeg是一个非常强大的多媒体处理工具&#xff0c;它可以用于视频和音频的录制、转换以及流处理。在流处理方面&#xff0c;FFmpeg可以用来推流&#xff0c;即将本地媒体…

Spring快速学习

目录 IOC控制反转 引言 IOC案例 Bean的作用范围 Bean的实例化 bean生命周期 DI 依赖注入 setter注入 构造器注入 自动装配 自动装配的方式 注意事项; 集合注入 核心容器 容器的创建方式 Bean的三种获取方式 Bean和依赖注入相关总结 IOC/DI注解开发 注解开发…

探索四川财谷通抖音小店:安全与信赖的购物新体验

在数字经济蓬勃发展的今天&#xff0c;抖音平台凭借其庞大的用户基础和强大的内容生态&#xff0c;逐渐成为了电商领域的一股不可忽视的力量。其中&#xff0c;四川财谷通抖音小店作为这一浪潮中的佼佼者&#xff0c;不仅以其丰富的商品种类和独特的品牌魅力吸引了众多消费者的…

【数据结构】排序 —— 快速排序(quickSort)

Hi~&#xff01;这里是奋斗的明志&#xff0c;很荣幸您能阅读我的文章&#xff0c;诚请评论指点&#xff0c;欢迎欢迎 ~~ &#x1f331;&#x1f331;个人主页&#xff1a;奋斗的明志 &#x1f331;&#x1f331;所属专栏&#xff1a;数据结构、LeetCode专栏 &#x1f4da;本系…

Python酷库之旅-第三方库Pandas(067)

目录 一、用法精讲 266、pandas.Series.dt.second属性 266-1、语法 266-2、参数 266-3、功能 266-4、返回值 266-5、说明 266-6、用法 266-6-1、数据准备 266-6-2、代码示例 266-6-3、结果输出 267、pandas.Series.dt.microsecond属性 267-1、语法 267-2、参数 …

集合基础知识及练习

import java.util.ArrayList;public class Solution {//将字符串转化为整数public static void main(String[] args) {ArrayList<String> listnew ArrayList();list.add("aaa");list.add("aaa");list.add("bbb");list.add("ccc"…