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

问题描述 投票:0回答:1

我有一个服务,它消耗了许多外部服务。我正在为每个服务创建属性文件,这些都是相当多的预定义属性,例如 twil.props、tweet.props、hubpot.props等。

因此,为了在运行时获得这些适当的数据,我使用的是 PropertiesLoaderUtils 像下面这样。

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

我想把这些属性放到POJO中,就像ConfigurationProperties一样,我为此设计了以下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中?

java spring spring-boot properties spring-cloud-config
1个回答
0
投票

正如在评论中所注意到的,这里唯一正确的解决方案包括零停机时间,即 @RefreshScope.

  1. 使用 spring cloud 配置依赖
<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地图的机会,其中bean key是一个bean名称。将上面的bean方法从 twilConfigtwil() 并像这样调用你的端点。/twil/foo (結構 是一个坏的端点路径)

© www.soinside.com 2019 - 2024. All rights reserved.