javaspringlazy-initializationspring-beanpost-processor

Can Spring init Bean(Factory)PostProcessor lazily?


Could anybody explain me it? After reading the documentation I didn't understand.

Can Spring init Bean(Factory)PostProcessor lazily or not?

https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-extension-factory-postprocessors

There is a such block that confuse me:

As with BeanPostProcessors , you typically do not want to configure BeanFactoryPostProcessors for lazy initialization. If no other bean references a Bean(Factory)PostProcessor, that post-processor will not get instantiated at all. Thus, marking it for lazy initialization will be ignored, and the Bean(Factory)PostProcessor will be instantiated eagerly even if you set the default-lazy-init attribute to true on the declaration of your element.


Solution

  • The correct answer to the question: "Can Spring init Bean(Factory)PostProcessor lazily?" is "NO". I checked it by myself. I created 2 classes:

    @Lazy
    @Component
    public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            System.out.println("bean factory!");
        }
    }
    

    and

    @Lazy
    @Component
    public class CustomBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("before init!");
            return bean;
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    }
    

    And run spring application. So, in console it was printed: "bean factory" and several times "before init", although I put @Lazy annotation on these classes.