Spring BeanPostProcessor 究竟是如何工作的? [英] How exactly does the Spring BeanPostProcessor work?

查看:32
本文介绍了Spring BeanPostProcessor 究竟是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Spring Core 认证,但我对 Spring 如何处理 beans 生命周期,特别是 bean 后处理器有一些疑问.

I am studying for the Spring Core certification an I have some doubts about how Spring handle the beans lifecycle and in particular about the bean post processor.

所以我有这个架构:

我很清楚这意味着什么:

It is pretty clear for me what it means:

以下步骤发生在加载 Bean 定义阶段:

  • @Configuration 类被处理和/或 @Components 被处理扫描和/或解析 XML 文件.

  • The @Configuration classes are processed and/or @Components are scanned for and/or XML files are parsed.

添加到 BeanFactory 的 Bean 定义(每个都在其 id 下索引)

Bean definitions added to BeanFactory (each indexed under its id)

特殊的BeanFactoryPostProcessor bean 被调用,它可以修改任何 bean 的定义(例如用于属性占位符值的替换).

Special BeanFactoryPostProcessor beans invoked, it can modify the definition of any bean (for example for the property-placeholder values replacements).

然后在beans创建阶段执行以下步骤:

  • 默认情况下,每个 bean 都会急切地实例化(以正确的顺序创建并注入其依赖项).

  • Each bean is eagerly instantiated by default (created in right order with its dependencies injected).

依赖注入后,每个 bean 都经过一个后处理可能会发生进一步配置和初始化的阶段.

After dependency injection each bean goes through a post-processing phase in which further configuration and initialization may occur.

在后处理之后,bean 被完全初始化并准备好使用(通过它的 id 跟踪直到上下文被销毁)

After post processing the bean is fully initialized and ready for use (tracked by its id until the context is destroyed)

好的,这对我来说很清楚,我也知道有两种类型的 bean 后处理器,它们是:

Ok, this is pretty clear for me and I also know that there are two types of bean post processors which are:

  • Initializers:根据指示初始化 bean(即@PostConstruct).

  • Initializers: Initialize the bean if instructed (i.e. @PostConstruct).

所有其他:允许额外配置,并且可以在初始化步骤之前或之后运行

我发布了这张幻灯片:

所以我很清楚初始化器 bean 的后处理器是什么(它们是用 @PostContruct 注释注释的方法,并且在 setter 之后立即自动调用方法(所以在依赖注入之后),我知道我可以用来执行一些初始化批处理(如上一个示例中填充缓存).

So it is very clear for me what does the initializers bean post processors (they are the methods annotated with @PostContruct annotation and that are automatically called immediately after the setter methods (so after the dependency injection), and I know that I can use to perform some initialization batch (as populate a cache as in the previous example).

但究竟是什么代表了另一个 bean 后处理器?当我们说这些步骤在初始化阶段之前或之后执行时,我们是什么意思?

But what exactly represents the other bean post processor? What do we mean when we say that these steps are performed before or after the initialization phase?

所以我的 bean 被实例化并注入了它的依赖项,然后初始化阶段完成(通过执行一个 @PostContruct 注释方法).在初始化阶段之前使用 Bean Post Processor 是什么意思?这意味着它发生在 @PostContruct 注释方法执行之前?这是否意味着它可能发生在依赖注入之前(在调用 setter 方法之前)?

So my beans are instantiated and its dependencies are injected, so then the initialization phase is completed (by the execution of a @PostContruct annotated method). What do we mean by saying that a Bean Post Processor is used before the initialization phase? It means that it happens before the @PostContruct annotated method execution? Does it means that it could happen before the dependency injection (before that the setter methods are called)?

当我们说它在初始化步骤之后执行时,我们究竟是什么意思.这意味着它发生在 @PostContruct 注释方法的执行之后,还是什么?

And what exactly do we mean when we say that it is performed after the initialization step. It means that it happens after that the execution of a @PostContruct annotated method, or what?

我可以很容易地理解为什么我需要一个 @PostContruct 带注释的方法,但我无法想象其他类型的 bean 后处理器的一些典型例子,你能告诉我一些典型的例子吗?什么时候用?

I can easily figure into my head why I need a @PostContruct annotated method but I can't figure some typical example of the other kind of bean post processor, can you show me some typical example of when are used?

推荐答案

Spring doc 解释了 使用 BeanPostProcessor 自定义 bean.BPP bean 是一种特殊的 bean,它在任何其他 bean 之前创建并与新创建的 bean 交互.通过这种构造,Spring 为您提供了通过自己实现一个 BeanPostProcessor 来连接和自定义生命周期行为的方法.

Spring doc explains the BPPs under Customizing beans using BeanPostProcessor. BPP beans are a special kind of beans that get created before any other beans and interact with newly created beans. With this construct, Spring gives you means to hook-up to and customize the lifecycle behavior simply by implementing a BeanPostProcessor yourself.

有一个像自定义的 BPP

Having a custom BPP like

public class CustomBeanPostProcessor implements BeanPostProcessor {

    public CustomBeanPostProcessor() {
        System.out.println("0. Spring calls constructor");
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println(bean.getClass() + "  " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println(bean.getClass() + "  " + beanName);
        return bean;
    }
}

将被调用并打印出每个创建的 bean 的类和 bean 名称.

would be called and print out the class and bean name for every created bean.

要了解该方法如何适应 bean 的生命周期,以及该方法的确切调用时间,请查看 docs

To undersand how the method fit the bean's lifecycle, and when exactly the method's get called check the docs

postProcessBeforeInitialization(Object bean, String beanName) 应用此 BeanPostProcessor 到任何 bean 之前的给定新 bean 实例初始化回调(如 InitializingBean 的 afterPropertiesSet或自定义初始化方法).

postProcessBeforeInitialization(Object bean, String beanName) Apply this BeanPostProcessor to the given new bean instance before any bean initialization callbacks (like InitializingBean's afterPropertiesSet or a custom init-method).

postProcessAfterInitialization(Object bean, String beanName) 应用此 BeanPostProcessor 到任何 bean 之后的给定新 bean 实例初始化回调(如 InitializingBean 的 afterPropertiesSet或自定义初始化方法).

postProcessAfterInitialization(Object bean, String beanName) Apply this BeanPostProcessor to the given new bean instance after any bean initialization callbacks (like InitializingBean's afterPropertiesSet or a custom init-method).

还有一点很重要

bean 已经填充了属性值.

The bean will already be populated with property values.

对于与 @PostConstruct 的关系,请注意此注解是声明 postProcessAfterInitialization 方法的便捷方式,当您通过在bean配置文件中注册CommonAnnotationBeanPostProcessor或指定.@PostConstruct 方法是在任何其他 postProcessAfterInitialization 之前还是之后执行取决于 order 属性

For what concerns the relation with the @PostConstruct note that this annotation is a convenient way of declaring a postProcessAfterInitialization method, and Spring becomes aware of it when you either by registerCommonAnnotationBeanPostProcessor or specify the <context:annotation-config /> in bean configuration file. Whether the @PostConstruct method will execute before or after any other postProcessAfterInitialization depends on the order property

可以配置多个 BeanPostProcessor 实例,并且可以通过设置来控制这些 BeanPostProcessor 的执行顺序订单属性.

You can configure multiple BeanPostProcessor instances, and you can control the order in which these BeanPostProcessors execute by setting the order property.

这篇关于Spring BeanPostProcessor 究竟是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆