在 Spring Cloud Config 中使用 @PropertySource - Git

Posted

技术标签:

【中文标题】在 Spring Cloud Config 中使用 @PropertySource - Git【英文标题】:Use of @PropertySource with Spring Cloud Config - Git 【发布时间】:2019-10-07 20:10:14 【问题描述】:

我正在使用@PropertySource 来配置一个配置类:

@Configuration
@PropertySource("classpath:/mongo-$env.properties")
public class MongoConfiguration 

mongo-$env.properties 文件位于类路径中。 这很好用。

我现在正在使用 Spring Cloud Config 将配置外部化到 Git: 所有 application.yml 文件都已迁移。 但是我不知道这是否可能以及如何将属性文件外部化,如@PropertySource 中声明的文件。

我做了什么: 我试图在 Git 中将 mongo-prod.properties 重命名为 application-prod.properties。 然后我将@PropertySource 更改为:

@PropertySource("file:///C://.../config-repo/application-prod.properties")

这是存储库的本地副本。这可行,但这只是一个硬编码的解决方案。

有更清洁的解决方案吗?

【问题讨论】:

【参考方案1】:

您可以使用@ConfigurationProperties 注释加载属性假设您已正确设置配置服务器。

示例 假设您的服务名称是 customer-service,并希望从配置服务器获取属性文件。

第 1 步在您的 git 存储库中添加客户属性。您还可以添加特定于环境的属性,例如

customer-qa.properties ,customer-dev.properties

现在加载这些属性

@Component
@ConfigurationProperties("customer-service")
@Data
public class CustomerServiceConfigurations 

    private String somePropertyname;

 

更多详情请查看以下示例Config Server

【讨论】:

我想继续使用 PropertySource 注释并为单独的属性组提供单独的文件,例如 mongo-$env.properties 用于 mongo 属性等。您描述的解决方案也对我有用,甚至不需要ConfigurationProperties 注释。由于对于这个特定示例,多个微服务需要配置,因此我将这些属性复制到 Git 的“通用”application-prod.yml 中。 您可以将常用的共享属性放在application.properties中。看看这个***.com/a/55933568/320087 我就是这么做的。我在 Git 中具有跨服务的特定 env (application-env.yml) 的公共属性,以及跨服务和跨 env (application.yml) 的公共属性。只是说我认为我可以在使用 Spring Cloud Config 时将 PropertySource 注释保留在代码中。但似乎不可能。 最后一件事是如何外部化 spring.profiles.include 但这是另一个问题***.com/questions/56163411/…

以上是关于在 Spring Cloud Config 中使用 @PropertySource - Git的主要内容,如果未能解决你的问题,请参考以下文章

Spring Cloud Config客户端使用

Spring Cloud Config教程客户端使用

在 Spring Cloud Config 中使用 @PropertySource - Git

spring.cloud.config.server.native.search-locations 不适用于 Spring Cloud Config 服务器中的占位符

Spring Cloud 学习 Spring Cloud Config

无法通过 spring.cloud.config.enabled:false 禁用 Spring Cloud Config