1

I have two @Lazy components, one initialized by the second.

Whenever I try to use @Value({"app.my.prop"}) over some variable nothing happens, the variable is empty.

If I have something like this:

@Lazy
@Repository
public class justAClassThatPerhapsCompiles{
    @Value("${app.my.prop}")
    String myProp; 

    @Lazy
    @Autowired
    Environment env;

    void justAFuncThatSomebodyWillTryToCompileMaybe(){
        env.getProperty("app.my.prop"); //env is null
        System.out.println(myProp); //myProp is null
    }
}

Again nothing happens, env is null at runtime.

How can I get properties inside the lazily initialized components?

Hohenheimsenberg
  • 935
  • 10
  • 25

1 Answers1

1

One option would be to use Constructor Injection to pass the values of Environment and the property to your class.

@Lazy
@Repository
public class JustAClassThatPerhapsCompiles {

    private final String myProp; 
    private final Environment env;

    public JustAClassThatPerhapsCompiles(Environment env, 
                                         @Value("${app.my.prop}") String myProp) {
      this.env = env;
      this.myProp = myProp;
    }

    void justAFuncThatSomebodyWillTryToCompileMaybe(){
        env.getProperty("app.my.prop"); //env should no longer be null
        System.out.println(myProp); //myProp should no longer be null
    }
}

Since Spring is still managing the life cycle of the object, Constructor Injection will allow it to pass the reference (env) and the property as it would in a regular object when it lazily initializes your bean.

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99