spring通过组合配置文件选择属性源

juud5qan  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(199)

我有多个由spring配置文件驱动的环境,比如 application-int.yml , application-dev.yml 等类似内容: application-int.ymlws: endpoint: http://my-soap-int-endpoint.com/ mock: http://my-soap-int-mock-endpoint.com/application-dev.yml ```
ws:
endpoint: http://my-soap-dev-endpoint.com/
mock: http://my-soap-dev-mock-endpoint.com/

我的目标是基于环境名称和 `mock` 配置文件包括: `ws.endpoint` 从 `application-dev.yml` 为了 `dev` 配置文件 `ws.endpoint` 从 `application-int.yml` 为了 `int` 配置文件 `ws.mock` 从 `application-dev.yml` 为了 `dev mock` 配置文件 `ws.mock` 从 `application-int.yml` 为了 `int mock` 配置文件
我需要把这个值解析成一个变量 `url` :

@Configuration
public class SoapConfiguration {

@Value("???")                  // based on 2 properties
private String wsUrl;

}

我希望避免仅基于 `@Profile` . 此外,我需要在公共属性文件中保留这两个变量(mock和non-mock)。
有没有一种既可读又可维护的好方法?
zpjtge22

zpjtge221#

你可以设置 wsUrl 在构造函数中。这不是一个优雅的解决方案,但它是有效的。注入 Environment 豆子给你的 SoapConfiguration 支票是 mock 配置文件处于活动状态。
代码示例:

@Configuration
public class SoapConfiguration {
    private final String wsUrl;

    public SoapConfiguration(Environment environment) {
        if (Arrays.asList(environment.getActiveProfiles()).contains("mock")) {
            this.wsUrl = environment.getProperty("ws.mock");
        } else {
            this.wsUrl = environment.getProperty("ws.endpoint");
        }
    }
}

相关问题