I have one POJO class which read properties from application.yaml file in spring boot. Here I need to set default value to groupId(to get when not given) based on combination of topic value and another string.
private String topic;
@Value("${topic}_test")
private String groupId;
I tried this but getting error as
Could not resolve placeholder 'topic' in value "${topic}_test
I create a variable and tried to access it in @Value but failed. Please provide any suggestion to access this
Let's say you have a property like this in your application.yml file
topic: myFavoriteTopic
The code below will assign the value "myFavoriteTopic" to variable groupId
if Spring is able to load the property with key topic
from application.yml. If it's not, it will assign the default value "my default topic".
@Value("${topic:my default topic}")
private String groupId;
To set null
as the default value, use:
@Value("${topic:#{null}}")
To use an empty String as the default value, use:
@Value("${topic:}")
In your code snippet you have a String topic
variable. For the Spring framework, this variable is not used in the property value retrieval. When you do @Value("${topic}")
, "topic" is the name of the key that Spring will look for in application.yml. The name of the key cannot be determined at runtime based on the value of a Java variable. The reason is that properties can be loaded before the class code executes.
Also in your code snippet, you use @Value("${topic}_test")
. What Spring does in this case is to concatenate "_test" to the value retrieved for property key topic. In my first example, groupId
would be assigned "myFavoriteTopic_test".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With