【问题标题】:Load array of pairs from application.yml从 application.yml 加载对数组
【发布时间】:2022-01-13 08:28:21
【问题描述】:

任务是从 application.yml 文件中填充对列表。 所以在我的 kotlin 代码中,我有这样的东西:

@Component
class LocalImageStore(
@Value("\${images.thumbnails_sizes}")
private val thumbnailsSizes: List<Pair<Int, Int>>
) : ImageStore
{
// unrelated code here
}

application.yml 文件中我有以下内容:

images:
  dir:
    path: images
  thumbnails_sizes: 
    - [150, 150]
    - [200, 200]
    - [400, 450]

所以我希望我的 thumbnailsSizes 将包含 .yml 文件中的对列表,但我看到的只是错误消息 Could not resolve placeholder 'images.thumbnails_sizes' in value "${images.thumbnails_sizes}"n 我没有找到在 .yml 文件中存储对列表的方法,因此请告知如何以正确的方式进行。

【问题讨论】:

    标签: spring-boot kotlin yaml


    【解决方案1】:

    尝试以下方法:

    images:
      dir:
        path: images
      thumbnails_sizes: 
        - 150: 150
        - 200: 200
        - 400: 450
    

    或者

    images:
      dir:
        path: images
      thumbnails_sizes: 
        - { 150: 150 }
        - { 200: 200 }
        - { 400: 450 }
    

    直接使用配置类而不是@Value。假设您有以下这些属性的类:

    @ConstructorBinding
    @ConfigurationProperties(prefix = "images")
    class ImagesConfiguration(@field:NestedConfigurationProperty val thumbnailsSizes: List<ThumbnailSize>)
    
    data class ThumbnailSize(val width: Int, val height: Int)
    

    您将LocalImageStore 更改为以下内容:

    @Component
    class LocalImageStore(private val imagesConfiguration: ImagesConfiguration) : ImageStore {
      // just use imagesConfiguration.thumbnailsSizes were needed
      // unrelated code here 
    }
    

    您可以在 YAML 中轻松配置,如下所示:

    images:
      dir:
        path: images
      thumbnails-sizes: 
        - width: 150
          height: 150
        - width: 200
          height: 200
        - width: 400
          height: 450
    

    【讨论】:

    • 据我了解,yaml 文件应该以 key: value 格式存储对?在我的情况下,它不像 key: value,它更像 {["width": 150, "height": 150], ["width": 200, "height": 200], ["width": 400, "height": 450]}。然后我应该创建用于存储宽高对的类并以某种方式从 .yml 文件中解析 json 数组吗?
    • 用一个类来做会更容易,更易读。
    • 我已经编辑了我的答案,请检查一下;)
    • 仍然看到错误:Could not resolve placeholder 'images.thumbnails_sizes' in value "${images.thumbnails_sizes}"
    • 正如我的回答所暗示的那样,您不能自动连接 ThumbnailSizeList&lt;ThumbnailSize&gt;,而是 ImagesConfigurationLocalImageStore 中。您可能需要将@ConfigurationPropertiesScan 添加到您的主类(带有@SpringBootApplication 的类)。试一试,让我知道结果;)
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 2016-12-01
    • 1970-01-01
    • 2019-11-23
    • 2020-03-07
    • 2017-08-18
    • 2018-12-21
    • 2023-04-10
    相关资源
    最近更新 更多