-2

I am reading a value from application.yml file: This is a global variable.

@Value("${config.key}")
    public String variable;

for My use case I need to the value of this variable to another global variable:

String secondVariable = variable;

logs show that the key is stored inside the variable but I assign secondVariable the value of first it gives null. The secondVariable need to be global as I need to assign it a updated value when the scheduler runs. What is the right way to achieve this?

1 Answers1

0

After the Constructor call, Java initialize member variable so

variable = null
String secondVariable = variable
secondVariable = null

the variable is initialized after context initialization if you are working with spring.

Solution :

if secondVariable has the same scope as variable you should use the same annotation :

@Value("${config.key}")
    public String secondVariable;
Abderrazzak Nejeoui
  • 1,496
  • 12
  • 9
  • 1
    thanks! but actually what I wanted to do was use the ```variable``` the first time the program runs and then use the ```secondVariable``` for the rest of the execution. Again use the variable only if the application is down and restarts. I solved this by just creating a function which takes both ```variable``` and ```secondVariable``` as parameter and return me the string according to my logic. Made life easier. thanks for the help though! much appreciated. – tobby singh Feb 24 '21 at 20:25