Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 477
AndreaNobili Avatar asked Oct 27 '16 08:10

AndreaNobili


2 Answers

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

like image 103
Per Lundberg Avatar answered Oct 12 '22 03:10

Per Lundberg


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
like image 4
h_ismaili Avatar answered Oct 12 '22 01:10

h_ismaili