Customizing the Nature of a Bean

1.6. Customizing the Nature of a Bean

The Spring Framework provides a number of interfaces you can use to customize the nature of a bean. This section groups them as follows:

Spring框架提供了许多接口,您可以使用它们自定义bean的性质。本节将它们分组如下:
  • 生命周期回调
  • ApplicationContextAware和BeanNameAware
  • 其他Aware接口

1.6.1. Lifecycle Callbacks

To interact with the container’s management of the bean lifecycle, you can implement the Spring InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() for the latter to let the bean perform certain actions upon initialization and destruction of your beans.

要与容器对bean生命周期的管理交互,您可以实现Spring InitializingBean和DisposableBean接口。容器对前者调用afterPropertiesSet(),对后者调用destroy(),让bean在初始化和销毁bean时执行某些操作。

The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring-specific interfaces. For details, see Using @PostConstruct and @PreDestroy.

If you do not want to use the JSR-250 annotations but you still want to remove coupling, consider init-method and destroy-method bean definition metadata.

JSR-250的@PostConstruct和@PreDestroy注解通常被认为是现代Spring应用程序中接收生命周期回调的最佳实践。使用这些注释意味着您的bean没有耦合到特定于spring的接口。详情请参见使用@PostConstruct和@PreDestroy。

如果您不想使用JSR-250注释,但仍然希望消除耦合,请考虑初始化方法和销毁方法bean定义元数据。

Internally, the Spring Framework uses BeanPostProcessor implementations to process any callback interfaces it can find and call the appropriate methods. If you need custom features or other lifecycle behavior Spring does not by default offer, you can implement a BeanPostProcessor yourself. For more information, see Container Extension Points.

在内部,Spring框架使用BeanPostProcessor实现来处理它可以找到的任何回调接口,并调用适当的方法。如果你需要定制特性或Spring默认不提供的其他生命周期行为,你可以自己实现一个BeanPostProcessor。有关更多信息,请参见容器扩展点。

In addition to the initialization and destruction callbacks, Spring-managed objects may also implement the Lifecycle interface so that those objects can participate in the startup and shutdown process, as driven by the container’s own lifecycle.

除了初始化和销毁回调,spring管理的对象还可以实现Lifecycle接口,以便这些对象可以参与启动和关闭过程,这是由容器自己的生命周期驱动的。

The lifecycle callback interfaces are described in this section.

本节将描述生命周期回调接口。
Initialization Callbacks

The org.springframework.beans.factory.InitializingBean interface lets a bean perform initialization work after the container has set all necessary properties on the bean. The InitializingBean interface specifies a single method:

org.springframework.beans.factory.InitializingBean接口允许bean在容器设置了bean的所有必要属性之后执行初始化工作。InitializingBean接口指定了一个方法:
void afterPropertiesSet() throws Exception;

We recommend that you do not use the InitializingBean interface, because it unnecessarily couples the code to Spring. Alternatively, we suggest using the @PostConstruct annotation or specifying a POJO initialization method. In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. With Java configuration, you can use the initMethod attribute of @Bean. See Receiving Lifecycle Callbacks. Consider the following example:

我们建议您不要使用InitializingBean接口,因为它不必要地将代码与Spring耦合。或者,我们建议使用@PostConstruct注释或指定POJO初始化方法。对于基于xml的配置元数据,可以使用init-method属性指定具有空无参数签名的方法名称。通过Java配置,您可以使用@Bean的initMethod属性。参见接收生命周期回调。考虑以下例子:
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {

    public void init() {
        // do some initialization work
    }
}

The preceding example has almost exactly the same effect as the following example (which consists of two listings):

上面的示例与下面的示例(包含两个清单)的效果几乎完全相同:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
        // do some initialization work
    }
}

However, the first of the two preceding examples does not couple the code to Spring.

但是,前面两个示例中的第一个没有将代码与Spring耦合。
Destruction Callbacks

Implementing the org.springframework.beans.factory.DisposableBean interface lets a bean get a callback when the container that contains it is destroyed. The DisposableBean interface specifies a single method:

实现了org.springframework.beans.factory.DisposableBean接口后,当包含bean的容器被销毁时,bean可以获得一个回调。disablebean接口指定了一个方法:
void destroy() throws Exception;

We recommend that you do not use the DisposableBean callback interface, because it unnecessarily couples the code to Spring. Alternatively, we suggest using the @PreDestroy annotation or specifying a generic method that is supported by bean definitions. With XML-based configuration metadata, you can use the destroy-method attribute on the <bean/>. With Java configuration, you can use the destroyMethod attribute of @Bean. See Receiving Lifecycle Callbacks. Consider the following definition:

我们建议您不要使用DisposableBean回调接口,因为它不必要地将代码与Spring耦合在一起。或者,我们建议使用@PreDestroy注释或指定bean定义支持的泛型方法。对于基于xml的配置元数据,可以在<bean/>上使用destroy-method属性。通过Java配置,您可以使用@Bean的destroyMethod属性。参见接收生命周期回调。考虑以下定义:
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {

    public void cleanup() {
        // do some destruction work (like releasing pooled connections)
    }
}

The preceding definition has almost exactly the same effect as the following definition:

上面的定义与下面的定义的效果几乎完全相同:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {

    @Override
    public void destroy() {
        // do some destruction work (like releasing pooled connections)
    }
}

However, the first of the two preceding definitions does not couple the code to Spring.

但是,前面两个定义中的第一个没有将代码与Spring耦合起来。

You can assign the destroy-method attribute of a <bean> element a special (inferred) value, which instructs Spring to automatically detect a public close or shutdown method on the specific bean class. (Any class that implements java.lang.AutoCloseable or java.io.Closeable would therefore match.) You can also set this special (inferred) value on the default-destroy-method attribute of a <beans> element to apply this behavior to an entire set of beans (see Default Initialization and Destroy Methods). Note that this is the default behavior with Java configuration.

您可以为<bean/>元素的destroy-method属性分配一个特殊的(推断的)值,它指示Spring自动检测特定bean类上的公共关闭或关闭方法。(任何实现java.lang的类。Autocloseable或java.io.Closeable因此会匹配。)您还可以在<beans/>元素的Default - Destroy -method属性上设置这个特殊的(推断的)值,以便将此行为应用到整个bean集(请参阅缺省初始化和销毁方法)。注意,这是Java配置的默认行为。
Default Initialization and Destroy Methods

When you write initialization and destroy method callbacks that do not use the Spring-specific InitializingBean and DisposableBean callback interfaces, you typically write methods with names such as init(), initialize(), dispose(), and so on. Ideally, the names of such lifecycle callback methods are standardized across a project so that all developers use the same method names and ensure consistency.

当您编写不使用spring特定的InitializingBean和DisposableBean回调接口的初始化和销毁方法回调时,您通常会编写具有init()、initialize()、dispose()等名称的方法。理想情况下,这种生命周期回调方法的名称在整个项目中是标准化的,以便所有开发人员使用相同的方法名称并确保一致性。

You can configure the Spring container to "look" for named initialization and destroy callback method names on every bean. This means that you, as an application developer, can write your application classes and use an initialization callback called init(), without having to configure an init-method="init" attribute with each bean definition. The Spring IoC container calls that method when the bean is created (and in accordance with the standard lifecycle callback contract described previously). This feature also enforces a consistent naming convention for initialization and destroy method callbacks.

您可以配置Spring容器来“查找”每个bean上的命名初始化并销毁回调方法名称。这意味着,作为应用程序开发人员,您可以编写应用程序类并使用名为init()的初始化回调,而不必为每个bean定义配置init-method="init"属性。Spring loC容器在创建bean时调用该方法(并且与前面描述的标准生命周期回调契约一致)。这个特性还强制对初始化和销毁方法回调使用一致的命名约定。

Suppose that your initialization callback methods are named init() and your destroy callback methods are named destroy(). Your class then resembles the class in the following example:

假设初始化回调方法命名为init(),销毁回调方法命名为destroy()。你的类类似于下面的例子:
public class DefaultBlogService implements BlogService {

    private BlogDao blogDao;

    public void setBlogDao(BlogDao blogDao) {
        this.blogDao = blogDao;
    }

    // this is (unsurprisingly) the initialization callback method
    public void init() {
        if (this.blogDao == null) {
            throw new IllegalStateException("The [blogDao] property must be set.");
        }
    }
}

You could then use that class in a bean resembling the following:

然后你可以在类似下面的bean中使用这个类:
<beans default-init-method="init">

    <bean id="blogService" class="com.something.DefaultBlogService">
        <property name="blogDao" ref="blogDao" />
    </bean>

</beans>

The presence of the default-init-method attribute on the top-level <beans/> element attribute causes the Spring IoC container to recognize a method called init on the bean class as the initialization method callback. When a bean is created and assembled, if the bean class has such a method, it is invoked at the appropriate time.

顶级<beans/>元素属性上的default-init-method属性会导致Spring IoC容器将bean类上名为init的方法识别为初始化方法回调。在创建和组装bean时,如果bean类有这样的方法,就会在适当的时候调用它。

You can configure destroy method callbacks similarly (in XML, that is) by using the default-destroy-method attribute on the top-level <beans/> element.

通过在顶级<beans/>元素上使用default-destroy-method属性,可以类似地配置销毁方法回调(即在XML中)。

Where existing bean classes already have callback methods that are named at variance with the convention, you can override the default by specifying (in XML, that is) the method name by using the init-method and destroy-method attributes of the <bean/> itself.

在现有bean类已经有了与约定不同命名的回调方法的地方,您可以通过使用<bean/>本身的init-method和destroy-method属性来指定(即在XML中)方法名称来重写缺省值。

The Spring container guarantees that a configured initialization callback is called immediately after a bean is supplied with all dependencies. Thus, the initialization callback is called on the raw bean reference, which means that AOP interceptors and so forth are not yet applied to the bean. A target bean is fully created first and then an AOP proxy (for example) with its interceptor chain is applied. If the target bean and the proxy are defined separately, your code can even interact with the raw target bean, bypassing the proxy. Hence, it would be inconsistent to apply the interceptors to the init method, because doing so would couple the lifecycle of the target bean to its proxy or interceptors and leave strange semantics when your code interacts directly with the raw target bean.

Spring容器保证在bean与所有依赖项一起提供之后立即调用已配置的初始化回调。因此,初始化回调是在原始bean引用上调用的,这意味着AOP拦截器等还没有应用到bean上。首先完全创建一个目标bean,然后应用一个AOP代理(例如)及其拦截器链。如果目标bean和代理是分开定义的,那么您的代码甚至可以绕过代理,与原始目标bean进行交互。因此,将拦截器应用于init方法是不一致的,因为这样做会将目标bean的生命周期与其代理或拦截器耦合起来,并在您的代码直接与原始目标bean交互时留下奇怪的语义。
Combining Lifecycle Mechanisms

As of Spring 2.5, you have three options for controlling bean lifecycle behavior:

在Spring 2.5中,您有三种方法来控制bean的生命周期行为:
  • InitializingBean和DisposableBean回调接口
  • 自定义init()和destroy()方法
  • @PostConstruct和@PreDestroy注解。您可以组合这些机制来控制给定的bean

If multiple lifecycle mechanisms are configured for a bean and each mechanism is configured with a different method name, then each configured method is run in the order listed after this note. However, if the same method name is configured — for example, init() for an initialization method — for more than one of these lifecycle mechanisms, that method is run once, as explained in the preceding section.

如果为一个bean配置了多个生命周期机制,并且每个机制都配置了不同的方法名,那么每个配置的方法都将按照本说明后面列出的顺序运行。但是,如果为这些生命周期机制中的多个配置了相同的方法名(例如,初始化方法的init()),那么该方法将运行一次,如上一节所述。

Multiple lifecycle mechanisms configured for the same bean, with different initialization methods, are called as follows:

  1. Methods annotated with @PostConstruct
  2. afterPropertiesSet() as defined by the InitializingBean callback interface
  3. A custom configured init() method
为同一个bean配置的多个生命周期机制,使用不同的初始化方法,调用如下:
  1. 用@PostConstruct注释的方法
  2. 由InitializingBean回调接口定义的afterPropertiesSet()方法
  3. 一个自定义配置的init()方法

Destroy methods are called in the same order:

  1. Methods annotated with @PreDestroy
  2. destroy() as defined by the DisposableBean callback interface
  3. A custom configured destroy() method
Destroy方法的调用顺序相同:
  1. 用@PreDestroy注释的方法
  2. 由DisposableBean回调接口定义的destroy()方法
  3. 一个自定义配置的destroy()方法
Startup and Shutdown Callbacks

The Lifecycle interface defines the essential methods for any object that has its own lifecycle requirements (such as starting and stopping some background process):

Lifecycle接口定义了任何有自己生命周期需求的对象的基本方法(比如启动和停止某个后台进程):
public interface Lifecycle {

    void start();

    void stop();

    boolean isRunning();
}

Any Spring-managed object may implement the Lifecycle interface. Then, when the ApplicationContext itself receives start and stop signals (for example, for a stop/restart scenario at runtime), it cascades those calls to all Lifecycle implementations defined within that context. It does this by delegating to a LifecycleProcessor, shown in the following listing:

任何spring管理的对象都可以实现Lifecycle接口。然后,当ApplicationContext本身接收到启动和停止信号时(例如,运行时的停止/重新启动场景),它将这些调用级联到该上下文中定义的所有生命周期实现。它通过委托给LifecycleProcessor来实现,如下所示:
public interface LifecycleProcessor extends Lifecycle {

    void onRefresh();

    void onClose();
}

Notice that the LifecycleProcessor is itself an extension of the Lifecycle interface. It also adds two other methods for reacting to the context being refreshed and closed.

注意,LifecycleProcessor本身就是Lifecycle接口的扩展。它还添加了另外两个方法来响应正在刷新和关闭的上下文。

Note that the regular org.springframework.context.Lifecycle interface is a plain contract for explicit start and stop notifications and does not imply auto-startup at context refresh time. For fine-grained control over auto-startup of a specific bean (including startup phases), consider implementing org.springframework.context.SmartLifecycle instead.

Also, please note that stop notifications are not guaranteed to come before destruction. On regular shutdown, all Lifecycle beans first receive a stop notification before the general destruction callbacks are being propagated. However, on hot refresh during a context’s lifetime or on stopped refresh attempts, only destroy methods are called.

注意,常规的org.springframework.context.Lifecycle接口是一个显式启动和停止通知的普通约定,并不意味着在上下文刷新时自动启动。对于特定bean的自动启动的细粒度控制(包括启动阶段),可以考虑实现org.springframework.context.SmartLifecycle。

此外,请注意,停止通知不保证在销毁之前。在常规关闭时,所有生命周期bean在传播常规销毁回调之前首先收到一个停止通知。但是,在上下文生命周期内的热刷新或停止刷新尝试时,只调用destroy方法。

The order of startup and shutdown invocations can be important. If a "depends-on" relationship exists between any two objects, the dependent side starts after its dependency, and it stops before its dependency. However, at times, the direct dependencies are unknown. You may only know that objects of a certain type should start prior to objects of another type. In those cases, the SmartLifecycle interface defines another option, namely the getPhase() method as defined on its super-interface, Phased. The following listing shows the definition of the Phased interface:

启动和关闭调用的顺序可能很重要。如果任何两个对象之间存在“依赖”关系,依赖方在其依赖方之后启动,在其依赖方之前停止。然而,有时候,直接依赖关系是未知的。您可能只知道某种类型的对象应该在另一种类型的对象之前开始。在这些情况下,SmartLifecycle接口定义了另一个选项,即在其超级接口phaseage上定义的getPhase()方法。下面的清单显示了phase界面的定义:
public interface Phased {

    int getPhase();
}

The following listing shows the definition of the SmartLifecycle interface:

下面列出了SmartLifecycle接口的定义:
public interface SmartLifecycle extends Lifecycle, Phased {

    boolean isAutoStartup();

    void stop(Runnable callback);
}

When starting, the objects with the lowest phase start first. When stopping, the reverse order is followed. Therefore, an object that implements SmartLifecycle and whose getPhase() method returns Integer.MIN_VALUE would be among the first to start and the last to stop. At the other end of the spectrum, a phase value of Integer.MAX_VALUE would indicate that the object should be started last and stopped first (likely because it depends on other processes to be running). When considering the phase value, it is also important to know that the default phase for any "normal" Lifecycle object that does not implement SmartLifecycle is 0. Therefore, any negative phase value indicates that an object should start before those standard components (and stop after them). The reverse is true for any positive phase value.

当启动时,最低阶段的对象首先启动。当停止时,按照相反的顺序进行。因此,实现SmartLifecycle并且getPhase()方法返回Integer的对象。MIN_VALUE是最先开始的,也是最后停止的。在频谱的另一端,一个整数的相位值。MAX_VALUE表示应该最后启动对象,首先停止对象(可能是因为它依赖于正在运行的其他进程)。当考虑阶段值时,知道任何“正常”生命周期对象没有实现SmartLifecycle的默认阶段是0也是很重要的。因此,任何负相位值都表示一个对象应该在这些标准组件之前启动(并在它们之后停止)。对于任何正相位值,反之成立。

The stop method defined by SmartLifecycle accepts a callback. Any implementation must invoke that callback’s run() method after that implementation’s shutdown process is complete. That enables asynchronous shutdown where necessary, since the default implementation of the LifecycleProcessor interface, DefaultLifecycleProcessor, waits up to its timeout value for the group of objects within each phase to invoke that callback. The default per-phase timeout is 30 seconds. You can override the default lifecycle processor instance by defining a bean named lifecycleProcessor within the context. If you want only to modify the timeout, defining the following would suffice:

SmartLifecycle定义的stop方法接受一个回调。在实现的关闭过程完成后,任何实现都必须调用回调函数的run()方法。这样就可以在必要的地方实现异步关机,因为LifecycleProcessor接口的默认实现DefaultLifecycleProcessor会等待每个阶段中调用该回调的对象组的超时值。每个阶段的默认超时是30秒。您可以通过在上下文中定义一个名为lifecycleProcessor的bean来重写默认的生命周期处理器实例。如果您只想修改超时,定义以下内容就足够了:
<bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
    <!-- timeout value in milliseconds -->
    <property name="timeoutPerShutdownPhase" value="10000"/>
</bean>

As mentioned earlier, the LifecycleProcessor interface defines callback methods for the refreshing and closing of the context as well. The latter drives the shutdown process as if stop() had been called explicitly, but it happens when the context is closing. The 'refresh' callback, on the other hand, enables another feature of SmartLifecycle beans. When the context is refreshed (after all objects have been instantiated and initialized), that callback is invoked. At that point, the default lifecycle processor checks the boolean value returned by each SmartLifecycle object’s isAutoStartup() method. If true, that object is started at that point rather than waiting for an explicit invocation of the context’s or its own start() method (unlike the context refresh, the context start does not happen automatically for a standard context implementation). The phase value and any "depends-on" relationships determine the startup order as described earlier.

如前所述,LifecycleProcessor接口还定义了用于刷新和关闭上下文的回调方法。后者驱动关闭过程,就像显式调用了stop()一样,但它发生在上下文关闭时。另一方面,'refresh'回调可以启用SmartLifecycle bean的另一个特性。当上下文被刷新时(在所有对象被实例化和初始化之后),该回调将被调用。这时,默认的生命周期处理器会检查每个SmartLifecycle对象的isAutoStartup()方法返回的布尔值。如果为真,则在该点启动该对象,而不是等待上下文或其自己的start()方法的显式调用(与上下文刷新不同,对于标准上下文实现,上下文启动不会自动发生)。如前所述,阶段值和任何“依赖”关系决定启动顺序。
Shutting Down the Spring IoC Container Gracefully in Non-Web Applications

This section applies only to non-web applications. Spring’s web-based ApplicationContext implementations already have code in place to gracefully shut down the Spring IoC container when the relevant web application is shut down.

本节只适用于非web应用。Spring基于web的ApplicationContext实现已经有了适当的代码,可以在相关web应用程序关闭时优雅地关闭Spring IoC容器。

If you use Spring’s IoC container in a non-web application environment (for example, in a rich client desktop environment), register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released. You must still configure and implement these destroy callbacks correctly.

如果您在非web应用程序环境中使用Spring的IoC容器(例如,在富客户机桌面环境中),请向JVM注册一个关闭挂钩。这样做可以确保安全关闭,并调用单例bean上的相关销毁方法,以便释放所有资源。您仍然必须正确地配置和实现这些销毁回调。

To register a shutdown hook, call the registerShutdownHook() method that is declared on the ConfigurableApplicationContext interface, as the following example shows:

要注册一个关机钩子,可以调用在ConfigurableApplicationContext接口上声明的registerShutdownHook()方法,如下所示:
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public final class Boot {

    public static void main(final String[] args) throws Exception {
        ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

        // add a shutdown hook for the above context...
        ctx.registerShutdownHook();

        // app runs here...

        // main method exits, hook is called prior to the app shutting down...
    }
}

1.6.2. `ApplicationContextAware` and `BeanNameAware`

When an ApplicationContext creates an object instance that implements the org.springframework.context.ApplicationContextAware interface, the instance is provided with a reference to that ApplicationContext. The following listing shows the definition of the ApplicationContextAware interface:

当ApplicationContext创建一个实现了org.springframework.context.ApplicationContextAware接口的对象实例时,该实例将被提供一个对该ApplicationContext的引用。下面的清单显示了ApplicationContextAware接口的定义:
public interface ApplicationContextAware {

    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

Thus, beans can programmatically manipulate the ApplicationContext that created them, through the ApplicationContext interface or by casting the reference to a known subclass of this interface (such as ConfigurableApplicationContext, which exposes additional functionality). One use would be the programmatic retrieval of other beans. Sometimes this capability is useful. However, in general, you should avoid it, because it couples the code to Spring and does not follow the Inversion of Control style, where collaborators are provided to beans as properties. Other methods of the ApplicationContext provide access to file resources, publishing application events, and accessing a MessageSource. These additional features are described in Additional Capabilities of the ApplicationContext.

因此,bean可以通过ApplicationContext接口或通过将引用转换为该接口的已知子类(例如ConfigurableApplicationContext,它公开了额外的功能),以编程方式操作创建它们的ApplicationContext。一种用途是对其他bean进行程序化检索。有时这种能力是有用的。但是,通常情况下,您应该避免使用它,因为它将代码与Spring耦合在一起,并且不遵循控制反转风格,在这种风格中,协作者被作为属性提供给bean。ApplicationContext的其他方法提供对文件资源的访问、发布应用程序事件和访问MessageSource。这些附加特性在ApplicationContext的附加功能中进行了描述。

Autowiring is another alternative to obtain a reference to the ApplicationContext. The traditional constructor and byType autowiring modes (as described in Autowiring Collaborators) can provide a dependency of type ApplicationContext for a constructor argument or a setter method parameter, respectively. For more flexibility, including the ability to autowire fields and multiple parameter methods, use the annotation-based autowiring features. If you do, the ApplicationContext is autowired into a field, constructor argument, or method parameter that expects the ApplicationContext type if the field, constructor, or method in question carries the @Autowired annotation. For more information, see Using @Autowired.

自动装配是另一种获取Applicationcontext引用的方法。传统的ongl构造函数和byType自动装配模式(如autotowiring collaborator中所述)可以分别为构造函数参数或setter方法参数提供ApplicationContext类型的依赖项。为了获得更大的灵活性,包括自动装配字段和多个参数方法的能力,可以使用基于注释的自动装配特性。如果这样做,ApplicationContext将被自动连接到字段、构造函数参数或方法参数中,如果有问题的字段、构造函数或方法携带@Autowired注释,则该字段、构造函数或方法需要ApplicationContext类型。有关更多信息,请参见使用@Autowired。

When an ApplicationContext creates a class that implements the org.springframework.beans.factory.BeanNameAware interface, the class is provided with a reference to the name defined in its associated object definition. The following listing shows the definition of the BeanNameAware interface:

当ApplicationContext创建一个实现org.springframework.bean .factory. beannameaware接口的类时,会为该类提供一个对其关联对象定义中定义的名称的引用。下面的清单显示了BeanNameAware接口的定义:
public interface BeanNameAware {

    void setBeanName(String name) throws BeansException;
}

The callback is invoked after population of normal bean properties but before an initialization callback such as InitializingBean.afterPropertiesSet() or a custom init-method.

在填充普通bean属性之后,但在初始化回调(如InitializingBean.afterPropertiesSet()或自定义初始化方法)之前调用回调。

1.6.3. Other `Aware` Interfaces

Besides ApplicationContextAware and BeanNameAware (discussed earlier), Spring offers a wide range of Aware callback interfaces that let beans indicate to the container that they require a certain infrastructure dependency. As a general rule, the name indicates the dependency type. The following table summarizes the most important Aware interfaces:

除了ApplicationContextAware和BeanNameAware(前面讨论过)之外,Spring还提供了广泛的Aware回调接口,这些接口让bean向容器表明它们需要特定的基础设施依赖项。通常,名称表示依赖类型。下表总结了最重要的Aware接口:
Name Injected Dependency Explained in...
ApplicationContextAware Declaring ApplicationContext. ApplicationContextAware and BeanNameAware
ApplicationEventPublisherAware Event publisher of the enclosing ApplicationContext. Additional Capabilities of the ApplicationContext
BeanClassLoaderAware Class loader used to load the bean classes. Instantiating Beans
BeanFactoryAware Declaring BeanFactory. The BeanFactory API
BeanNameAware Name of the declaring bean. ApplicationContextAware and BeanNameAware
LoadTimeWeaverAware Defined weaver for processing class definition at load time. Load-time Weaving with AspectJ in the Spring Framework
MessageSourceAware Configured strategy for resolving messages (with support for parametrization and internationalization). Additional Capabilities of the ApplicationContext
NotificationPublisherAware Spring JMX notification publisher. Notifications
ResourceLoaderAware Configured loader for low-level access to resources. Resources
ServletConfigAware Current ServletConfig the container runs in. Valid only in a web-aware Spring ApplicationContext. Spring MVC
ServletContextAware Current ServletContext the container runs in. Valid only in a web-aware Spring ApplicationContext. Spring MVC

Note again that using these interfaces ties your code to the Spring API and does not follow the Inversion of Control style. As a result, we recommend them for infrastructure beans that require programmatic access to the container.

再次注意,使用这些接口将您的代码与Spring API绑定在一起,并且不遵循控制反转样式。因此,对于需要对容器进行编程访问的基础结构bean,我们推荐使用它们。
posted @ 2022-09-09 15:10  丶Jan  阅读(28)  评论(0)    收藏  举报