当前位置: 代码网 > it编程>编程语言>Java > Spring Boot读取配置文件的五种方式小结

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

2025年04月25日 Java 我要评论
spring boot 提供了灵活多样的方式来读取配置文件(如 application.yml 或 application.properties),本文介绍几种常见的读取方式。1. 配置文件位置与加载

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读取配置文件的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com