Spring Boot读取配置文件的五种方式小结

2025-04-25 17:50

本文主要是介绍Spring Boot读取配置文件的五种方式小结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进...

Spring Boot 提供了灵活多样的方式来读取配置文件(如 application.yml 或 application.properties),本文介绍几种常见的读取方式。

1. 配置文件位置与加载顺序

Spring Boot 默认从以下位置加载配置文件(优先级从高到低):

命令行参数(如:--server.port=8081)

application.properties / application.yml(位于 classpath:/config/)

classpath:/application.properties 或 application.yml

外部配置中心(如 Nacos、Spring Cloud Config)

2. 读取配置文件的方式汇总

Spring Boot 提供了多种读取配置文件的方式。

方式一:使用 @Value 注解读取配置

这种方式适合读取单个简单配置项。可以用来注入配置文件中的值,也可以指定默认值,防止配置项缺失时抛出异常 。

配置文件:

app:
  name: order-v
  version: v1

示例代码:

@Component
public class AppProperties {

    @Value("${app.name:order}")
    private String name;

    @Value("${app.version:v1.0.0}")
    private String version;

    public void print() {
        System.out.println("App Name: " + name);
        System.out.println("App Version: " + version);
    }
}
  • : 后面就是默认值
  • 当配置文件中没有对应的值时,会使用默认值
  • 如果配置项存在对应的值,默认值不生效

测试代码:

@RestController
@RequestMapping("/test")
@AllArgsConstructor
public class TestController {

    private final AppProperties appProperties;

    @RequestMapping("/print")
    public void print() {
        appProperties.print();
    }
}

✅ 优点:

简单直接,适用于读取单个变量

❌ 缺点:

不支持嵌套结构、不支持批量绑定、不利于维护

方式二:使用 @ConfigurationProperties 自动绑定配置类(推荐)

适合绑定多个字段、嵌套结构、List、Map等复杂配置。

配置文件:

app:
  name: order-v
  version: v1
  servers:
    - http://dev-server:8080
    - http://test-server:8081
    - http://prod-server:8082
  metadata:
    author: Alice
    version: 1.0.2
    website: https://emp.com
  modules:
    user:
      enabled: true
      path: /user
    admin:
      enabled: false
      pyElssdbath: /admin

配置类示例代码:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import Java.util.List;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "app")
@Data
public class AppProperties {

    private String name;

    // List 示例
    private List<String> servers;

    // Map<String, String> 示例
    private Map<String, String> metadata;

    // Map<String, 自定义对象> 示例
    private Map<String, Module> modules;

    @Data
    public static class Module {
        private boolean enabled;
        private String path;
    }
    
    public void print() {
        System.out.println("name: " + name);
        System.out.println("servers: " + servers);
        System.out.println("metadata: " + metadata);
        System.out.println("modules: " + modules);
    }
}

使用示例:

import com.example.xiaoshitou.config.AppConfigProperties;
import com.example.xiaoshitou.config.AppProperties;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/test")
@AllArgsConstructor
public class TestController {

    private final AppProperties appProperties;
    private final AppConfigProperties appConfigProperties;

    @RequestMapping("/print")
    public void print() {
        appProperties.print();
    }

    @RequestMapping("/printConfig")
    public void printConfig() {
        appConfigProperties.print();
    }
}

✅ 优点:

  • 支持对象结构、嵌套对象、List、Map
  • 支持校验(配合 @Validated)
  • 强类型绑定,IDE 支持友好

❌ 缺点:

需要额外的类定义

方式三:使用 Environment 编程式读取配置

适合动态读取、条件判断场景。

示例代码:

import com.example.xiaoshitou.config.AppConfigProperties;
import com.example.xiaoshitou.config.AppProperties;
import com.example.xiaoshitou.config.SmsConfig;
import lombok.AllArgsConstructor;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/***
 * @title
 * @author shijiangyong
 * @date 2025/4/24 17:28
 **/
@RestController
@RequestMapping("/test")
@AllArgsConstructor
public class TestController {

    private final AppProperties appProperties;
    private final AppConfigProperties appConfigProperties;
    private final Environment env;

    @RequestMapping("/print")
    public void print() {
        appProperties.print();
    }

    @RequestMjavascriptapping("/printConfig")
    public void printConfig() {
        appConfigProperties.print();
    }

    @RequestMapping("/printEnv")
    public void printEnv() {
        String name = env.getProperty("app.name");
        System.out.println("app.name = " + name);
    }

}

✅ 优点:

  • 动态、灵活,支持条件判断
  • 可用于第三方库或工具类中

❌ 缺点:

可读性差,不支持自动绑定

方式四:加载自定义配置文件(@PropertySource)

当你需要读取非 application.yml 的配置文件时使用。

自定义配置文件 sms-config.properties:

sms.sign=aliyun
sms.template.code=TPL001

示例代码:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/***
 * @title
 * @author shijiangyong
 * @date 2025/4/25 10:08
 **/
@Configuration
@PropertySource("classpath:sms-config.properties")
@ConfigurationProperties(prefix = "sms")
@Data
public class SmsConfig {
    private String sign;
    private Template template;

    @Data
    public static class Template {
        private String code;
    }

    public void print() www.chinasem.cn{
        System.out.println("sign : " + sign);
        System.out.println("template.code : " + template.getCode());
    }
}

使用示例:

import com.example.xiaoshitou.config.AppConfigProperties;
import com.example.xiaoshitou.config.AppProperties;
import com.example编程.xiaoshitou.config.SmsConfig;
import lombok.AllArgsConstructor;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/***
 * @title
 * @author shijiangyong
 * @date 2025/4/24 17:28
 **/
@RestController
@RequestMapping("/test")
@AllArgsConstructor
public class TestController {

    private final AppProperties appProperties;
    private final AppConfigProperties appConfigProperties;
    private final SmsConfig smsConfig;
    private final Environment env;

    @RequestMapping("/print")
    public void print() {
        appProperties.print();
    }

    @RequestMapping("/printConfig")
    public void printConfig() {
        appConfigProperties.print();
    }

    @RequestMapping("/printEnv")
    public void printEnv() {
        String name = env.getProperty("app.name");
        System.out.println("app.name = " + name);
    }


    @RequestMapping("/smsConfig")
    public void smsConfig() {
        smsConfig.print();
    }

}

✅ 优点:

  • 支持加载自定义配置文件
  • 可与 @ConfigurationProperties 搭配使用

❌ 缺点:

  • 不支持 .yml 格式
  • 不支持动态刷新

方式五:多环境配置(多 Profile)

适用于开发、测试、生产环境的配置隔离。

配置文件:

# application-dev.yml
app:
  name: DevApp

# application-prod.yml
app:
  name: ProdApp

激活方式:

在 application.yml 中设置:

spring:
  profiles:
    active: dev

或通过启动参数:

--spring.profiles.active=prod

✅ 优点:

  • 多环境隔离,配置清晰
  • 支持组合激活多个 profile

总结

场景推荐方式
读取单个简单值@Value
读取嵌套结构、对象@ConfigurationProperties
动态读取Environment
非默认配置文件@PropertySource
多环境支持多 profile

以上就是Spring Boot读取配置文件的五种方式小结的详细内容,更多关于Spring Boot读取配置文件的资料请关注China编程(www.chinasem.cn)其它相关文章!

这篇关于Spring Boot读取配置文件的五种方式小结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154369

相关文章

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

golang程序打包成脚本部署到Linux系统方式

《golang程序打包成脚本部署到Linux系统方式》Golang程序通过本地编译(设置GOOS为linux生成无后缀二进制文件),上传至Linux服务器后赋权执行,使用nohup命令实现后台运行,完... 目录本地编译golang程序上传Golang二进制文件到linux服务器总结本地编译Golang程序

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直