0

The following produces a null error ("A" is null), but I am not sure why. Is the bean instantiated before the property value is set?

package org.ets.readtogether.queuing;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("Abean")
public class Test {

    @Value("${send.timeout.secs}")
    public Integer A;

    public int B = A * 1000;
}

2 Answers2

3

Try this:

@Component("Abean")
public class Test {

    @Value("${send.timeout.secs}")
    public Integer A;

    public int B;

    @PostConstruct
    public void init() {
       B = A * 1000;
    }
}

Good example here

Essex Boy
  • 7,565
  • 2
  • 21
  • 24
2

Spring adds all the dependencies injected in an object after instantiating it. Object instantiation precedes any @Autowired dependency injection or @Value value assignment done by Spring.

The instantiation of your class's object fails even before Spring has the object to inject dependencies because the statement public int B = A * 1000; is called during object instantiation.

In order to assign the variable B a value after Spring has finished all injections, perform the operation in either a @PostConstruct method or in an @AutoWired constructor.

   public int B; // remove the assignment here.

   @PostConstruct
   public void postConstruct () {
       this.B = A * 1000;
   }

The above method would be called after the object has been instantiated and after Spring has done its work.

Pranjal
  • 351
  • 1
  • 5