Search Suggest

Spring Boot: Lazy Init Configuration Example


Make your Spring Boot app start faster using LazyInitConfiguration and implement with BeanFactoryPostProcessor.

@Configuration
public class LazyInitConfiguration implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (String beanName : beanFactory.getBeanDefinitionNames()) {
beanFactory.getBeanDefinition(beanName).setLazyInit(true);
}
}
}

Spring Boot introduces the spring.main.lazy-initialization property, making it easier to configure lazy initialization across the whole application.

Setting the property value to true means that all the beans in the application will use lazy initialization.

Let's configure the property in our application.yml configuration file:
spring:
main:
lazy-initialization: true

Or, if it's the case, in our application.properties file:
spring.main.lazy-initialization=true

This configuration affects all the beans in the context. So, if we want to configure lazy initialization for a specific bean, we can do it through the @Lazy approach.

Even more, we can use the new property, in combination with the @Lazy annotation, set to false.
Or in other words, all the defined beans will use lazy initialization, except for those that we explicitly configure with @Lazy(false).

Here's the result. It became just a little bit faster.
Benchmark                                          Mode  Cnt  Score   Error  Units
MyBenchmark.
case01_FluxBaseline ss 10 2.938 ± 0.287 s/op
MyBenchmark.
case02_WithLazyInit ss 10 2.844 ± 0.129 s/op

Reference:

Đăng nhận xét