【问题标题】:Two environments in the same application同一应用程序中的两个环境
【发布时间】:2019-03-07 08:09:08
【问题描述】:

是否可以为不同的配置文件构建环境(具有中继属性源)?

例如:当应用程序使用 prod 配置文件运行时,我希望拥有用于 dev 配置文件的配置 bean。

我正在使用 Spring Boot 2(带有新的 Binder API)

感谢任何帮助。

P.S.:我想要相同的配置对象,但具有配置文件特定的值。

示例: 应用程序.yml

spring:
   profiles: dev
server:
   address: 127.0.0.1
---
spring:
   profiles: prod
server:
   address: 192.168.1.120

配置 bean:

@Component
@ConfigurationProperties("server")
@Validated
public static class ServerConf {
   private final InetAddress address;
...
}

主要目标是将 ServerConf 作为与活动配置文件相关的 bean 和与特定配置文件相关的 ServerConf 类的对象集或 ServerConfProd、ServerConfDev 等 bean 集

理想情况下,我正在寻找类似的东西:

StandardEnvironment env = new StandardEnvironment();
env.setActiveProfiles("prod");
MutablePropertySources propertySources = env.getPropertySources();

propertySources.addLast(new ResourcePropertySource("classpath:application-prod.properties"));
propertySources.addLast(new ResourcePropertySource("classpath:application.properties"));
ServerConf prodServerConf = Binder.get(env).bind("server", Bindable.of(ServerConf.class)).get();

它可以工作,但有很多缺点:验证不起作用,手动设置属性源...

【问题讨论】:

  • 你可以在两个不同的端口上配置相同的值
  • 如果我明白你在看@Profile("dev") 注释
  • 谢谢,但不,情况有点复杂

标签: spring-boot


【解决方案1】:

是的,您可以设置多个活动配置文件,如下所示:

spring.prifiles.active:
- prod
- dev

使用这种方法,所有用@Profiles("prod")@Profiles("dev") 定义的bean 都将被初始化。请注意,不应有任何模棱两可的 bean 定义。


如果您更愿意将 prod 设置为活动配置文件,您仍然可以告诉 Spring 包含其他配置文件:

spring.profiles.include:
  - dev
  - other

更多参考请查看profiles chapter

更新

你的想法行不通:一个属性会覆盖另一个。

我会将serverConf.address 作为地图处理:

application.yml

spring:
  profiles: dev
server:
  addresses:
    dev: 127.0.0.1
---
spring:
  profiles: prod
server:
  addresses:
    prod: 192.168.1.120

ServerConf.java

@Component
@ConfigurationProperties("server")
@Validated
public class ServerConf {
   private final Map<String, InetAddress> addresses = new HashMap<>();
   //...
}

这样,如果您激活这两个配置文件,您将获得一个包含 2 个键(devprod)的地图。我个人觉得它有点难看,但应该可以解决你的问题。

【讨论】:

  • 谢谢,但在我的情况下它不起作用。我想要配置相同属性的特定值。
  • 能否编辑您的问题并提供一些示例?
  • 写了一个例子。希望这将有助于澄清我想要什么。 @noiaverbale
  • 感谢您的宝贵时间,但这不是我想要的
  • 您可能想更详细地解释您的用例我看不出答案不起作用的原因,
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2021-02-26
  • 2015-07-03
  • 1970-01-01
相关资源
最近更新 更多