How can I set the default behavior of lazy init in Spring Boot?
Asked Answered
B

2

5

I am working on my first Spring Boot application and I have the following problem.

I want to set the that for default all beans are lazy loaded. I know that I can add the @Lazy to all my @Component beans but I want that for default all beans are setted at lazy...

In Spring Boot I don't have an XML configuration file or a configuration class but I only have an application.properties configuration file.

So, how can I set that the default behavior for all the bean is lazy=true

Benbena answered 27/10, 2016 at 8:20 Comment(4)
not 100% sure to close as duplicate but may help: #15093398Nephrolith
Add a BeanFactoryPostProcessor that sets the LazyInit property of all bean definitions to lazy. You might want to exclude everything that is marked as an INFRASTRUCTURE bean. Or simply place @Lazy on the main application class.Rocambole
@M.Deinum Ok, I placed the Lazy annotation on my main application and it works fine. I think that use a BeanFactoryPostProcessor is too much at this time. But for personal culture: when is better use the BeanFactoryPostProcessor way? If you write your previous comment as a response I will happy to accept your answer :-)Benbena
I think programmatically choosing when to adopt LazyInit would be one reason to opt for a BeanFactoryPostProcessor. E.g. for some tests it might be easier to have LazyInit.Anecdotist
N
7

To implement a BeanFactoryPostProcessor that sets lazy initialization by default (which can be required if you are e.g. defining some of the beans dynamically, outside of your @Configuration class(es)), the following approach worked for me:

@Component
public class LazyBeansFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory ) throws BeansException {
        for ( String name : beanFactory.getBeanDefinitionNames() ) {
            beanFactory.getBeanDefinition( name ).setLazyInit( true );
        }
    }
}

This essentially puts the @Lazy annotation on all your @Component and @Services. You might want to invent a mechanism to annotate classes with @Eager if you go this route, or just hardwire a list in the LazyBeansFactoryPostProcessor above.

Further reading

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/BeanFactoryPostProcessor.html

Namedropping answered 18/11, 2019 at 7:35 Comment(0)
A
5

Since the version 2.2.2.RELEASE of spring-boot you can use the property below in your application.properties file

spring.main.lazy-initialization=true

for further reading and a good example please refer to

https://www.baeldung.com/spring-boot-lazy-initialization
https://spring.io/blog/2019/03/14/lazy-initialization-in-spring-boot-2-2
Aubervilliers answered 1/12, 2020 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.