'Spring setting @value from another variable

Is it possible to set @Value from another variable

For eg.

System properties : firstvariable=hello ,secondvariable=world

@Value(#{systemProperties['firstvariable'])
String var1;

Now I would like to have var2 to be concatenated with var1 and dependant on it , something like

    @Value( var1 + #{systemProperties['secondvariable']
    String var2;

public void message(){ System.out.printlng("Message : " + var2 );


Solution 1:[1]

No, you can't do that or you will get The value for annotation attribute Value.value must be a constant expression.

However, you can achieve same thing with following

In your property file

firstvariable=hello
secondvariable=${firstvariable}world

and then read value as

@Value("${secondvariable}")
private String var2;

Output of System.out.println("Message : " + var2 ) would be Message : helloworld.

Solution 2:[2]

As the question use the predefined systemProperties variable with EL expiration.
My guess is that the meaning was to use java system properties (e.g. -D options).

As @value accept el expressions you may use

@Value("#{systemProperties['firstvariable']}#systemProperties['secondvariable']}")
private String message;

You said

Now I would like to have var2 to be concatenated with var1 and dependent on it

Note that in this case changing var2 will not have effect on message as the message is set when the bean is initialized

Solution 3:[3]

In my case (using Kotlin and Springboot together), I have to escape "$" character as well. Otherwise Intellij IDEA gives compile time error:

Implementation gives error:

@Value("${SCRIPT_PATH}")
private val SCRIPT_PATH: String = ""

Error: An annotation argument must be a compile-time constant

Solution:

@Value("\${SCRIPT_PATH}")
private val SCRIPT_PATH: String = ""

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yogesh Badke
Solution 2 Haim Raman
Solution 3