如何在Spring Boot的引导文件中正确设置不同的Spring配置文件(以便针对不同的云配置服务器)?

24

我们针对每个环境都有不同的配置服务器。每个Spring Boot应用程序应该针对其相应的配置服务器进行定位。我尝试通过在bootstrap.properties文件中设置配置文件来实现此目的,例如:

spring.application.name=app-name
spring.cloud.config.uri=http://default-config-server.com

---
spring.profiles=dev
spring.cloud.config.uri=http://dev-config-server.com

---
spring.profiles=stage
spring.cloud.config.uri=http://stage-config-server.com

---
spring.profiles=prod
spring.cloud.config.uri=http://prod-config-server.com

然后我设置了 cla -Dspring.profiles.active=dev,但加载的配置服务器总是在文件中设置的上一个服务器(即在上述设置中将加载生产配置服务器,如果删除生产,则将加载stage)。

是否可能为云配置服务器设置引导配置文件? 我遵循了这个例子,但似乎无法使其正常工作。 顺便说一下,这些配置文件可以很好地工作以加载正确的配置(即如果活动配置文件为dev,则将加载app-name-dev.properties),但未从正确的配置服务器获取。


2
这只适用于yaml文件,而不适用于属性文件(据我所知)。只需添加bootstrap-[profile].properties,例如bootstrap-dev.properties,其中包含所需的(覆盖的)配置。 - M. Deinum
3个回答

29

在单个文件中指定不同的配置文件仅支持YAML文件,而不适用于属性文件。对于属性文件,请指定特定于环境的bootstrap-[profile].properties以覆盖默认bootstrap.properties中的属性。

因此,在您的情况下,您将获得4个文件:bootstrap.propertiesbootstrap-prod.propertiesbootstrap-stage.propertiesbootstrap-dev.properties

但是,您也可以仅提供默认的bootstrap.properties,并在启动应用程序时通过传递-Dspring.cloud.config.uri=<desired-uri>来覆盖属性。

java -jar <your-app>.jar -Dspring.cloud.config.uri=<desired-url>

这将优先于默认配置的值。


在 Boot 2.4 中,您可以在 .properties 文件中使用带有助手的魔术注释 #---,如 spring.config.activate.on-cloud-platformspring.config.activate.on-profile - gavenkoa

9
I solved a similar problem with an environment variable in Docker. 

bootstrap.yml

spring:
  application:
    name: dummy_service
  cloud:
    config:
      uri: ${CONFIG_SERVER_URL:http://localhost:8888/}
      enabled: true
  profiles:
    active: ${SPR_PROFILE:dev}

Dockerfile

ENV CONFIG_SERVER_URL=""
ENV SPR_PROFILE=""

Docker-compose.yml

version: '3'

services:

  dummy:
    image: xxx/xxx:latest
    restart: always
    environment:  
      - SPR_PROFILE=docker
      - CONFIG_SERVER_URL=http://configserver:8888/
    ports:
      - 8080:8080
    depends_on:
      - postgres
      - configserver
      - discovery

3
为什么不在Docker中设置SPRING_PROFILES_ACTIVE(在环境变量中),并跳过bootstrap.yml中的sprig.profiles.active - LarryW

0

@LarryW(我无法在同一评论中回答):

我猜显式添加属性的优点是,它允许您在未设置环境变量的情况下添加默认值(在本例中为“dev”)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接