Spring可以懒惰地初始化Bean(Factory)PostProcessor吗?

时间:2018-11-12 17:41:28

标签: java spring lazy-initialization spring-bean post-processor

有人可以向我解释吗?阅读文档后,我听不懂。

Spring可以懒惰地初始化Bean(Factory)PostProcessor吗?

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

有一个这样的方块使我感到困惑:

  

与BeanPostProcessors一样,您通常不想为延迟初始化配置BeanFactoryPostProcessors。如果没有其他bean引用Bean(Factory)PostProcessor,则该后处理器将完全不会实例化。因此,将其标记为延迟初始化将被忽略,即使您在元素声明时将default-lazy-init属性设置为true,Bean(Factory)PostProcessor也会被实例化。

1 个答案:

答案 0 :(得分:0)

该问题的正确答案:“ Spring是否可以懒惰地初始化Bean(Factory)PostProcessor?” “否” 。我自己检查了一下。我创建了2个课程:

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

@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;
    }
}

并运行spring应用程序。因此,尽管我在这些类上添加了@Lazy批注,但在控制台中却打印了“ bean factory”和“ init之前”多次。