Home > Enterprise >  Load array of pairs from application.yml
Load array of pairs from application.yml

Time:12-09

The task is to fill list of pairs from application.yml file. So in my kotlin code I've got something like this:

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

Inside of application.yml file I've got following:

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

So I expected that my thumbnailsSizes will contain the list of pairs from the .yml file, but all I see is error message Could not resolve placeholder 'images.thumbnails_sizes' in value "${images.thumbnails_sizes}"n I didn't find the way I can store list of pairs in .yml file, so please advise how to do it in a right way.

CodePudding user response:

Try the following approaches:

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

Or

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

Use a configuration class instead of @Value directly. Assuming that you have the following classes for these properties:

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

data class ThumbnailSize(val width: Int, val height: Int)

And you change the LocalImageStore to the following:

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

You can easily configure this in YAML as follows:

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