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

lazy-initialization, spring, spring-boot

Solution

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 `@Service`s. 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

Problem

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

Original source

Related problems