Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Read YAML with multiline property value over @Value

Tags:

spring

yaml

Currently I'm implement a YAML File over @PropertySouce and read the Property itself over @Value. But now I have a multiline Property in my YAML File and want to read it the same way. (I want to store my sql Queries outside of my code)

I know, that I can indicate a multiline YAML String over ">" or ">-" or "|". But when I try this and read the Property over @Value, I'm only getting the ">" as result in my String. So, is there a way to read the multiline YAML Property completly?

I know, that I can escape each line with a backslash, but this is not the best solution for me.

So for e.g. I want to read the key "multilinekey" in my test.yml:

multilinekey: >
   Hi, I am a multiline String.
   But I can't get readed over @Value by spring.

And want to implement this value in my Code as follow:

@PropertySource("classpath:/test.yml")
public class myTestClass
   @Value("${multilinekey}")
   private String multiline;

   ...
}

Is there any way to do this?

Or is there a better way to outsource my sql Queries in own files and include them easyly over @Value?

like image 574
Carsten Schmitt Avatar asked Nov 23 '25 19:11

Carsten Schmitt


1 Answers

This works fine for me:

controller.java

@Value("${str}")
String str;

@GetMapping("/probe")
public String probe(){
    return str;
}

application.yaml

str:"This is a very long sentence
    that spans several lines in the YAML
    but which will be rendered as a string
    with NO carriage returns."
like image 97
Muhammad Inshal Avatar answered Nov 27 '25 01:11

Muhammad Inshal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!