2

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 );
soorapadman
  • 4,451
  • 7
  • 35
  • 47
sash84
  • 85
  • 1
  • 3
  • 8

3 Answers3

8

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.

Yogesh Badke
  • 4,249
  • 2
  • 15
  • 23
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

Haim Raman
  • 11,508
  • 6
  • 44
  • 70
0

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 = ""
kaan bobac
  • 729
  • 4
  • 8