从application.yml加载对数组



任务是从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文件中存储对列表的方法,所以请建议如何以正确的方式进行存储。

尝试以下方法:

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

最新更新