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?

11
  • @Value{"app.my.prop"}) will never compile, please post the actual code Commented Mar 5, 2019 at 22:19
  • is justAClassThatPerhapsCompiles a Spring component? Commented Mar 5, 2019 at 22:27
  • 1
    can you inject the Environment somewhere eagerly? Commented Mar 5, 2019 at 22:42
  • 1
    Does if work if you use constructor injection for myProp and env? Commented Mar 5, 2019 at 22:44
  • 1
    Have a look at this answer as a workaround: Is it possible to @Lazy init a Spring @Value? Commented Mar 5, 2019 at 22:45

1 Answer 1

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.

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

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.