1

I have the following bean but he value of add is 0.0. But when I take off the @Value annotation and hard code the values it works.

What is wrong

public class MyBean{
@Value("${app.intA}")
private double a;

 @Value("${app.intB}")
private double b;

private double add = a+b;

public double getA(){
return a; // gives 2.4
}

 public double getB(){
return b; // gives 1.5
}

public double getAdd(){
return add; // always 0.0
}

}
Jeeppp
  • 1,553
  • 3
  • 17
  • 39
  • 1
    An object (and therefore its fields) are initialized before Spring has a chance to use reflection to process `@Value`. At the time `add` is initialized, `a` and `b` have their default value of 0. – Sotirios Delimanolis Aug 31 '17 at 20:44
  • The duplicate mentions `@Autowired`, but the behavior is the same for `@Value`. Also note that field initialization statements are copied into the constructor code. – Sotirios Delimanolis Aug 31 '17 at 20:45
  • Added a couple more duplicates which explain this behavior and give you workarounds. – Sotirios Delimanolis Aug 31 '17 at 20:48

0 Answers0