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 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Java中如何正确的停掉线程

《Java中如何正确的停掉线程》Java通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映