4

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)

Community
  • 1
  • 1
Nick Grealy
  • 24,216
  • 9
  • 104
  • 119

1 Answers1

6

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;
}
Maciej Walkowiak
  • 12,372
  • 59
  • 63