簡體   English   中英

PropertiesLoaderUtils.loadProperties 如何在運行時使用 Spring 映射到配置 POJO?

[英]How PropertiesLoaderUtils.loadProperties mapped to Configuration POJO using Spring at Runtime?

我有一項服務,它消耗許多外部服務。 我正在為它們中的每一個創建屬性文件,這些是相當少的預定義屬性,例如twil.props、tweet.props、hubpot.props 等

為了在運行時獲得這些屬性,我正在使用PropertiesLoaderUtils ,如下所示:

Resource resource = new ClassPathResource("/"+apiname +".properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);

我想像 ConfigurationProperties 一樣將這些屬性放入 POJO,為此我設計了以下 POJO:

public class APIConfig {

    private Integer paginationPerPage;

    private String paginationKeyword;

    private String paginationStyle;

    private String countParamKeyword;

    private String countKey;

    private String offsetKey;
}

我將以這樣的方式維護屬性文件,以便可以輕松地將它們映射到 Config POJO:

twil.properties 的屬性

api.paginationPerPage=10
api.paginationKeyword=limit
api.paginationStyle=offset
api.countParamKeyword=count
api.countKey=count
api.offsetKey=offset

那么我可以通過使用 Spring Boot / Spring 實用程序、配置等中的任何一個將其直接放入給定的 POJO 中嗎?

正如評論中所注意到的,這里唯一正確的解決方案包括零停機時間,即@RefreshScope

  1. 使用 spring 雲配置依賴
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
  1. 添加到您的代碼
@Configuration
class SomeConfiguration {
    @Bean
    @RefreshScope
    @ConfigurationProperties("twil.props")
    APIConfig twilConfig() {
        return new ApiConfig()
    }

    @Bean
    @RefreshScope
    @ConfigurationProperties("tweet.props")
    APIConfig tweetConfig() {
        return new ApiConfig()
    }

}

用法: @Autowire APIConfig tweetConfig; 對任何豆子
調用/refresh端點以通過來自屬性源的新值刷新 bean

請與 Spring 生態系統統一解決方案。

例如,如果您希望動態依賴於@PathVariable

private Map<String, AppConfig> sourceToConfig;

@GetMapping("/{source}/foo")
public void baz(@PathVariable source) {
     AppConfig revelantConfig = sourceToConfig.get(source);
     ...
}

Spring 提供了自動收集 bean 的 map 的機會,其中 bean 鍵是 bean 名稱。
將上面的 bean 方法從twilConfig重命名為twil()並調用您的端點,例如: /twil/footwilConfig是端點的錯誤路徑)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM