Spring Cloud——Spring Cloud Alibaba 2021 Nacos Config bootstrap 配置文件失效解决方案

本文解决SpringCloud2020环境下Bootstrap配置文件加载失败的问题,介绍SpringBoot2.4版本后配置加载的变化及修复方法。

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

基本概念

微服务是基于Spring Cloud框架搭建的,Spring Cloud Config作为服务配置中心。
业务服务只配置服务名称、启用环境和config的URL地址,其他都配置在配置中心,例如服务端口、服务注册中心地址等。可在开发环境(dev)、测试环境(test)和生产环境(prod)分别配置。
所以预想的启动流程是:先加载配置文件,再启动服务。
添加配置文件:bootstrap.properties或者bootstrap.yml。

环境配置

Spring Boot 2.4.5
Spring Cloud 2020.0.0
Spring Cloud Alibaba 2021.1

问题描述

没有加载到bootstrap.properties文件,bootstrap.yml同样无效。

问题分析

从Spring Boot 2.4版本开始,配置文件加载方式进行了重构。

另外也有配置的默认值变化,如下:

Spring Boot 2.3.8.RELEASE

package org.springframework.cloud.bootstrap;
public class BootstrapApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        if ((Boolean)environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class, true)) {

Spring Boot 2.4.2

package org.springframework.cloud.util;
public abstract class PropertyUtils {
    public static boolean bootstrapEnabled(Environment environment) {
        return (Boolean)environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class, false) || MARKER_CLASS_EXISTS;
    }

官方文档

https://docs.spring.io/spring-cloud-config/docs/current/reference/html/#config-first-bootstrap
在这里插入图片描述

解决方案

方法一:添加依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>

原来的bootstrap.properties或者bootstrap.yml不需要任何修改。
方法二:设置启动参数或者环境变量
IDEA环境: select Run/Debug Configurations > Override parameters 中添加 spring.cloud.bootstrap.enabled=true
命令列: java -jar -Dspring.cloud.bootstrap.enabled=true gateway.jar

参考文章

Spring Cloud 2020 bootstrap 配置文件失效
Spring Cloud 2020.0.0 版本 bootstrap.yml 失效的原因與解決

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Starzkg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值