Spring参考文档翻译08--IOC容器06

1.6. Customizing the Nature of a Bean

自定义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 Framework 提供了许多接口,您可以使用它们来自定义 bean 的性质。本节将它们分组如下:

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 生命周期的管理进行交互,可以实现 SpringInitializingBeanDisposableBean接口。容器要求 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 注释但仍想移除耦合,请考虑init-methoddestroy-methodbean 定义元数据。

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:

在容器为 bean 设置了所有必要的属性后,该org.springframework.beans.factory.InitializingBean接口允许 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 配置,您可以initMethod使用 @Bean. 请参阅接收生命周期回调。考虑以下示例:

<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 在包含它的容器被销毁时获得回调。该 DisposableBean接口指定了一个方法:

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 的配置元数据,您可以destroy-method使用<bean/>. 通过 Java 配置,您可以destroyMethod使用@Bean. 请参阅 接收生命周期回调。考虑以下定义:

<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类上的公共“close”或“shutdown”方法。(因此,任何实现“java.lang.AutoCloseable”或“java.io.Closeable”的类都将匹配。)您还可以在<beans>元素的default destroy method属性上设置这个特殊的(推断)值,以将此行为应用于整个bean集(请参阅[default Initialization and destroy Methods](Core Technologies工厂生命周期默认初始化销毁方法)。注意,这是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 IoC容器在创建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”属性来类似地配置destroy方法回调(在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 生命周期行为:

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:

为同一个bean配置的多个生命周期机制,不同的初始化方法,调用如下:

  1. Methods annotated with @PostConstruct

    用注释的方法@PostConstruct

  2. afterPropertiesSet() as defined by the InitializingBean callback interface

    afterPropertiesSet()InitializingBean回调接口定义

  3. A custom configured init() method

    自定义配置init()方法

Destroy methods are called in the same order:

销毁方法的调用顺序相同:

  1. Methods annotated with @PreDestro

    用注释的方法@PreDestroy

  2. destroy() as defined by the DisposableBean callback interface

    destroy()DisposableBean回调接口定义

  3. A custom configured destroy() method

    自定义配置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自身接收到启动和停止信号时(例如,对于运行时的停止/重新启动场景),它会将这些调用级联到Lifecycle该上下文中定义的所有实现。它通过委托给 a 来做到这一点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。另外,请注意,停止通知不能保证在销毁之前发出。在常规关闭时,所有Lifecyclebean 在传播一般销毁回调之前首先收到停止通知。但是,在上下文的生命周期内进行热刷新或停止刷新尝试时,只会调用销毁方法。

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接口定义了另一个选项,即getPhase()在其超接口上定义的方法, Phased. 以下清单显示了Phased接口的定义:

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_值将是最先启动和最后停止的值之一。在频谱的另一端,相位值为整数。MAX_VALUE`表示对象应该最后启动,然后首先停止(可能是因为它取决于要运行的其他进程)。在考虑阶段值时,同样重要的是要知道,任何未实现“SmartLifecycle”的“正常”Lifecycle对象的默认阶段为“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()”被显式调用一样,但它发生在上下文关闭时。另一方面,“刷新”回调启用了“SmartLifecycle”bean的另一个功能。刷新上下文时(在所有对象实例化和初始化之后),将调用该回调。此时,默认生命周期处理器检查每个“SmartLifecycle”对象的“isAutoStartup()”方法返回的布尔值。如果为“true”,则该对象将在该点启动,而不是等待显式调用上下文或其自己的“start()”方法(与上下文刷新不同,对于标准上下文实现,上下文启动不会自动发生)。如前所述,“阶段”值和任何“取决于”关系决定启动顺序。

Shutting Down the Spring IoC Container Gracefully in Non-Web Applications

在非web应用程序中优雅地关闭Spring IoC容器

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:

要注册关闭挂钩,请调用接口registerShutdownHook()上声明的方法ConfigurableApplicationContext,如以下示例所示:

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

ApplicationContextAware和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。上下文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”的引用的另一种替代方法。传统的构造函数'和按类型'自动布线模式(如[autowiring Collaborators]中所述)。可以分别为构造函数参数或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.beans.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()自定义 init 方法)之前调用回调。

1.6.3. Other Aware Interfaces

其他Aware接口

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:

除了ApplicationContextAwareBeanNameAware(前面讨论)之外,Spring 提供了广泛的Aware回调接口,让 bean 向容器指示它们需要特定的基础设施依赖项。作为一般规则,名称表示依赖类型。下表总结了最重要的Aware接口:

NameInjected DependencyExplained in…
ApplicationContextAwareDeclaring ApplicationContext.ApplicationContextAware and BeanNameAware
声明ApplicationContext.
ApplicationEventPublisherAwareEvent publisher of the enclosing ApplicationContext.Additional Capabilities of the ApplicationContext
封闭的事件发布者ApplicationContext
BeanClassLoaderAwareClass loader used to load the bean classes.Instantiating Beans
类加载器用于加载 bean 类。实例化 Bean
BeanFactoryAwareDeclaring BeanFactory.The BeanFactory API
声明BeanFactory.
BeanNameAwareName of the declaring bean.ApplicationContextAware and BeanNameAware
声明 bean 的名称。
LoadTimeWeaverAwareDefined weaver for processing class definition at load time.Load-time Weaving with AspectJ in the Spring Framework
定义的编织器,用于在加载时处理类定义。
MessageSourceAwareConfigured strategy for resolving messages (with support for parametrization and internationalization).Additional Capabilities of the ApplicationContext
用于解析消息的配置策略(支持参数化和国际化)。
NotificationPublisherAwareSpring JMX notification publisher.Notifications
Spring JMX 通知发布者。
ResourceLoaderAwareConfigured loader for low-level access to resources.Resources
为对资源进行低级访问而配置的加载程序。
ServletConfigAwareCurrent ServletConfig the container runs in. Valid only in a web-aware Spring ApplicationContext.Spring MVC
当前ServletConfig容器在其中运行。仅在可感知网络的 Spring 中有效 ApplicationContext
ServletContextAwareCurrent ServletContext the container runs in. Valid only in a web-aware Spring ApplicationContext.Spring MVC
当前ServletContext容器在其中运行。仅在可感知网络的 Spring 中有效 ApplicationContext

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,并且不遵循 Inversion of Control 样式。因此,我们建议将它们用于需要以编程方式访问容器的基础设施 bean。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值