3

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 );

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I need syntax to concat inside @Value
If your end objective is to concatenate value of var1 and var2, why don't you simply introduce an instance method as follow String getVar2() { return var1 + var2; }
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.