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

 更新时间:2025年04月25日 10:50:33   作者:颇有几分姿色  
Spring Boot 提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了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
      path: /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();
    }

    @RequestMapping("/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() {
        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读取配置文件的资料请关注脚本之家其它相关文章!

相关文章

  • Spring MVC拦截器(Interceptor)的定义和配置过程

    Spring MVC拦截器(Interceptor)的定义和配置过程

    这篇文章主要介绍了Spring MVC拦截器(Interceptor)的定义和配置过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • SpringBoot集成DJL实现图片分类功能

    SpringBoot集成DJL实现图片分类功能

    DJL是一个使用Java API简化模型训练、测试、部署和使用深度学习模型进行推理的开源库深度学习工具包,开源的许可协议是Apache-2.0,本文给大家介绍了SpringBoot集成DJL实现图片分类功能,需要的朋友可以参考下
    2024-10-10
  • jvm原理之SystemGC源码分析

    jvm原理之SystemGC源码分析

    这篇文章主要介绍了jvm源码分析之SystemGC的完全解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-01-01
  • java接口幂等性的实现方式

    java接口幂等性的实现方式

    本文介绍了在不同层面上实现Java接口幂等性的方法,包括使用幂等表、Nginx+Lua和Redis、以及SpringAOP,通过这些方法,可以确保接口在多次请求时只执行一次,避免重复处理和数据不一致,每种方法都有其适用场景和优势,通过实际测试验证了幂等性逻辑的有效性
    2025-01-01
  • Java编程访问权限的控制代码详解

    Java编程访问权限的控制代码详解

    这篇文章主要介绍了Java编程访问权限的控制代码详解,涉及包名,公共的和私有的等相关内容,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • Springboot 1.5.7整合Kafka-client代码示例

    Springboot 1.5.7整合Kafka-client代码示例

    这篇文章主要介绍了Springboot 1.5.7整合Kafka-client代码示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • 手把手教你写一个SpringBoot+gRPC服务

    手把手教你写一个SpringBoot+gRPC服务

    本文将在本地环境下搭建gRPC客户端和服务端,并成功建立通讯发送消息的方式,从而帮助大家深入了解gRPC在Spring Boot项目中的应用,有需要的小伙伴可以参考下
    2023-12-12
  • idea out目录与target目录的区别详解

    idea out目录与target目录的区别详解

    这篇文章主要介绍了idea out目录与target目录的区别详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • 关于springmvc-servlet中的配置小知识详解

    关于springmvc-servlet中的配置小知识详解

    这篇文章主要介绍了关于springmvc-servlet中的配置小知识详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Java数据结构和算法之冒泡,选择和插入排序算法

    Java数据结构和算法之冒泡,选择和插入排序算法

    这篇文章主要为大家介绍了Java冒泡,选择和插入排序算法 ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-01-01

最新评论