Spring-boot读取多个配置文件

本文介绍了一种在项目中同时加载多个配置文件的方法,通过设置spring.profiles.active属性来指定加载特定的配置文件,实现了从Git获取配置并结合本地配置文件进行应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于工作原因,一个项目需要读取多个配置文件,经过网上一番搜索,成功实现目标,现将实现过程做如下记录,以供参考。


  • 核心配置文件

resources 目录下有两个文件,声明下我项目的配置文件已放在git》> 上,bootstrap.properties 文件用已从git上获取我的配置文件,新建application-global.yml 文件用来做测试,文件目录如下
这里写图片描述

  • 配置文件内容
    在bootstrap.properties配置文件中通过spring.profiles.active属性来设置,其值对应{profile}值,如:spring.profiles.active=global就会加载application-global.yml 配置文件内容,具体如下所示:
spring.cloud.config.uri=http://
spring.cloud.config.label=profiles
spring.application.name=
spring.cloud.config.profile=global
spring.profiles.active= global

程序启动会先浏览bootstrap.properties文件,然后获取git上配置文件启动,最后加载application-global.yml文件这样就实现多个配置文件同时读取。

application-global.yml配置文件内容如下:
REG_USER_ACCOUNT_EXIST: "用户已注册"
REG_SBK_ZC: "该社保卡已经被注册"
  • 创建接口:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.env.Environment;

@RestController
@Api(description = "异常类")
@RequestMapping("/global")
public class GlobalController {

    @Autowired  
    private Environment env;  

    @ApiOperation(value = "异常名称")
    @ApiImplicitParam(name = "code", value = "异常编码", required = true, paramType = "query")
    @GetMapping("/code")   
    public String code(@RequestParam String code) { 
        return "message:"+env.getProperty(code);  
    }  

}

启动程序,测试成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值