Home > Mobile >  Reading keys with square brackets in YAML files from Spring
Reading keys with square brackets in YAML files from Spring

Time:04-26

I have a .yml file that one of the fields looks like this

  a:
    b:
      "[/folder/**]": "file:./src/"

How can I access this field in Spring using @Value?

I tried the following but all failed with "Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder"

@Value("${a.b./folder/**}") private File path;
@Value("${a.b.[/folder/**]}") private File path;
@Value("${a.b.\\[/folder/**\\]}") private File path;

CodePudding user response:

Kotlin:

@SpringBootTest
class TestExample {

    @Value("\${a.b.[/folder/**]}")
    lateinit var file: File

    @Test
    fun test() {
        // ".${File.separator}src" on Windows => .\src
        // ".${File.separator}src" on Linux => ./src
        assertEquals(".${File.separator}src", file.path)
    }
}

It also works with and without the "file:" prefix.

a:
  b:
    "[/folder/**]": "./src/"

CodePudding user response:

Your path key is in double quotes.
You must add double quotes in @Value property string like below.

@Value("${a.b.\"[/folder/**]\"}")
private File path;
  • Related