5

Is it possible to @Lazy init a Spring @Value?

e.g.

@Lazy
@Value("${someConfig}")
private String someConfig;

The scenario I'm specifically referring to, is a variable which is set via JNDI, and an embedded Tomcat container, which has some of it's JNDI variables initialised during Spring Boot loading... other scenarios I could think of where you'd want JIT variable population: It's "expensive" to retrieve a variable and you don't want to impact startup time, the variable isn't available at application startup, etc.

The above code gives the following error:

java.lang.IllegalArgumentException: Cannot subclass final class java.lang.String

I imagine you could possibly achieve lazy-loaded variables by using a @ConfigurationProperties bean?

A follow up question: Can/Would a @Value-initialised variable be reinitialised (without an app restart), if the underlying variable source is changed (e.g. JNDI on the server)? i.e. re-retrieved

(I'm in the process of trying these last two scenarios)

3
  • 1
    No, to your follow up question, not for a field in a singleton bean. But if you managed to declare the bean as singleton and get a new instance each time, that field would get initialized to the current value each time. Commented May 4, 2016 at 23:52
  • @SotiriosDelimanolis Thanks! Commented May 4, 2016 at 23:53
  • 4
    As a note on the specific error: @Lazy is implemented by replacing the field with a proxy, which can't be done if the field's declared type is a final class. Commented May 5, 2016 at 0:02

1 Answer 1

7
+50

You can give a try to such a setup. Downside is that it requires beans using this variable to be also declared as @Lazy.

@Bean(name = "myVar")
@Lazy
String foo(@Value("${someConfig}") String someConfig) {
    return someConfig;
}

@Component
@Lazy
class SomeComponent {

    @Autowired
    @Qualifier("myVar")
    String myVar;
}
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.