Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read variable or concatenate one property in @Value annotation of spring boot

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

like image 211
esha ingle Avatar asked Mar 05 '23 00:03

esha ingle


1 Answers

Default value

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:}")

Get key name from a variable

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.

_test suffix

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".

like image 173
Paulo Merson Avatar answered Mar 26 '23 21:03

Paulo Merson