Home > Blockchain >  Lazy load spring auto configuration
Lazy load spring auto configuration

Time:07-27

I have dependency in my spring boot project which fetches values of some properties using Spring's EnvironmentPostProcessor. Now these properties are database credentials and not everyone has access to the credential since there is no dev environment for the db in question. I just want to change the configuration that the credentials don't get fetched on dev or local environment on application startup as that would result in a error and the application will fail to start.

Class A implements EnvironmentPostProcessor{}

I tried to use @Lazy annotation on the Class Annoteted with @ConfigurationProperties. I also tried using my own BeanFactoryPostProcessor (with @Order(HighestPrecedence) to programmatically set the A to lazy load, but it gets called before my BeanFactoryPostProcessor's postProcessBeanFactory method. Is what I'm trying to achieve possible and am I going about it the wrong way?

CodePudding user response:

@Lazy is only to be used with @Bean or @Component (Or any @Component-based annotations ex. @Service)

Take note: You can also add it to a @Configuration class, but that just means that all Beans in the class are annotated with @Lazy

@Lazy is a bit of a weird annotation in general; it should be seen as an IF possible then lazy load. If some other bean needs the lazy bean, the lazy bean will be initialized. (It's like the Pirate code, more of a guideline than an enforced rule)

Finally, marking @ConfigurationProperties with @Lazy seems a bit odd. As Spring will need these Configuration property "beans" to create the Spring Context.

However, the common use case for @Lazy is a failing database connection, preventing the application from starting. See the question if that is what you are running into. Summary: You can configure your repositories to be lazy-loaded with:

spring.data.jpa.repositories.bootstrap-mode=lazy

Last remark (Me just guessing)

If you wish to change properties once your application is already running, I would look at the following tutorial. It goes into manually reloading configuration and also @RefreshScope.

CodePudding user response:

According to documentation EnvironmentPostProcessors must be registered via META-INF/spring.factories:

Allows for customization of the application's Environment prior to the application context being refreshed. EnvironmentPostProcessor implementations have to be registered in META-INF/spring.factories, using the fully qualified name of this class as the key. Implementations may implement the Ordered interface or use an @Order annotation if they wish to be invoked in specific order.

  • Related