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 性质的接口。本节将它们按以下方式分组:
1.6.1. 生命周期回调
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 初始化和销毁时执行特定操作。
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.
JSR-250 @PostConstruct 和 @PreDestroy 注解通常被认为是现代 Spring 应用程序接收生命周期回调的最佳实践。使用这些注解意味着你的
Bean 不会与 Spring 特定的接口耦合。有关详细信息,请参阅使用 @PostConstruct 和 @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 注解但仍然想去除耦合,请考虑使用 init-method 和 destroy-method 的 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. 生命周期回调接口在本节中描述。
初始化回调
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 执行初始化工作。
InitializingBean 接口指定了一个方法:
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 属性来指定具有 void 无参数签名的方法的名称。使用
Java 配置时,你可以使用 initMethod 属性。请参阅接收生命周期回调。考虑以下示例:
The preceding example has almost exactly the same effect as the following example (which consists of two listings): 前一个例子几乎与以下例子(由两个列表组成)有相同的效果:
However, the first of the two preceding examples does not couple the code to Spring. 然而,前两个例子中的第一个没有将代码与 Spring 耦合。
Be aware that @PostConstruct and initialization methods in general are executed within the container’s singleton
creation lock. The bean instance is only considered as fully initialized and ready to be published to others after
returning from the @PostConstruct method. Such individual initialization methods are only meant for validating the
configuration state and possibly preparing some data structures based on the given configuration but no further
activity
with external bean access.
请注意, @PostConstruct 和一般初始化方法都在容器单例创建锁内执行。只有在从 @PostConstruct 方法返回后,bean
实例才被视为完全初始化并准备好发布给其他组件。这样的单个初始化方法仅用于验证配置状态,并根据给定的配置可能准备一些数据结构,但不会进行与外部
bean 访问的进一步活动。
Otherwise there is a risk for an initialization deadlock.
否则存在初始化死锁的风险。
For a scenario where expensive post-initialization activity is to be triggered, e.g. asynchronous database
preparation
steps, your bean should either implement SmartInitializingSingleton.afterSingletonsInstantiated() or rely on the
context refresh event: implementing ApplicationListener<ContextRefreshedEvent> or declaring its annotation
equivalent
@EventListener(ContextRefreshedEvent.class). Those variants come after all regular singleton initialization and
therefore outside of any singleton creation lock.
对于需要触发昂贵的初始化活动的情况,例如异步数据库准备步骤,你的 bean 应实现
SmartInitializingSingleton.afterSingletonsInstantiated() 或依赖于上下文刷新事件:实现
ApplicationListener<ContextRefreshedEvent> 或声明其注解等效 @EventListener(ContextRefreshedEvent.class)
。这些变体在所有常规单例初始化之后,因此位于任何单例创建锁之外。
Alternatively, you may implement the (Smart)Lifecycle interface and integrate with the container’s overall
lifecycle
management, including an auto-startup mechanism, a pre-destroy stop step, and potential stop/restart callbacks (see
below).
或者,你可以选择实现 (Smart)Lifecycle 接口,并将其与容器的整体生命周期管理集成,包括自动启动机制、预销毁停止步骤以及潜在的停止/重启回调(见下文)。
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:
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:
The preceding definition has almost exactly the same effect as the following definition:
However, the first of the two preceding definitions does not couple the code to 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 for @Bean methods in Java configuration classes.
For extended shutdown phases, you may implement the Lifecycle interface and receive an early stop signal before
the
destroy methods of any singleton beans are called. You may also implement SmartLifecycle for a time-bound stop
step
where the container will wait for all such stop processing to complete before moving on to 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.
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.
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:
You could then use that class in a bean resembling the following:
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.
You can configure destroy method callbacks similarly (in XML, that is) by using the default-destroy-method
attribute
on the top-level <beans/> element.
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.
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.
As of Spring 2.5, you have three options for controlling bean lifecycle behavior:
The InitializingBean and
DisposableBean callback interfaces
Custom init() and destroy() methods
The @PostConstruct and @PreDestroy annotations. You can
combine
these mechanisms to control a given 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.
Multiple lifecycle mechanisms configured for the same bean, with different initialization methods, are called as follows:
Methods annotated with @PostConstruct
afterPropertiesSet() as defined by the InitializingBean callback interface
A custom configured init() method
Destroy methods are called in the same order:
Methods annotated with @PreDestroy
destroy() as defined by the DisposableBean callback interface
A custom configured destroy() method
启动和关闭回调
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 接口定义了任何具有自身生命周期要求(如启动和停止某些后台进程)的对象的基本方法:
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
实现。它是通过委托给以下列表中的 LifecycleProcessor 来实现的:
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.
请注意,常规的 org.springframework.context.Lifecycle
接口是一个用于显式启动和停止通知的纯合约,并不表示在上下文刷新时自动启动。
For fine-grained control over auto-startup and for graceful stopping of a specific bean (including startup and stop
phases), consider implementing the extended org.springframework.context.SmartLifecycle interface instead.
为了对自动启动进行细粒度控制,以及实现特定 bean(包括启动和停止阶段)的优雅停止,请考虑实现扩展的
org.springframework.context.SmartLifecycle 接口。
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.
此外,请注意,停止通知不保证在销毁之前到来。在常规关闭时,所有 Lifecycle
首先接收到停止通知,然后才传播到一般销毁回调。然而,在上下文生命周期中的热刷新或在停止刷新尝试中,只调用销毁方法。
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 接口定义了另一个选项,即在其超接口
Phased 上定义的 getPhase() 方法。以下列表显示了 Phased 接口的定义:
The following listing shows the definition of the SmartLifecycle interface:
以下列表显示了 SmartLifecycle 接口的定义:
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.
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:
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
豆子的另一个功能得以启用。当上下文被刷新(所有对象都已实例化和初始化后),该回调被调用。在那个时刻,默认的生命周期处理器检查每个
SmartLifecycle 对象的 isAutoStartup() 方法返回的布尔值。如果 true ,则在该点启动该对象,而不是等待上下文或其自身的
start() 方法的显式调用(与上下文刷新不同,标准上下文实现中的上下文启动不会自动发生)。 phase 值和任何“依赖”关系决定了启动顺序,如前所述。
优雅地关闭非 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 应用程序。基于 Web 的 Spring 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. 如果你在非 Web 应用环境中使用 Spring 的 IoC 容器(例如,在富客户端桌面环境中),请向 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. 这样做确保了优雅的关闭,并在你的单例 bean 上调用相关的销毁方法,以便释放所有资源。你仍然必须正确配置和实现这些销毁回调。
To register a shutdown hook, call the registerShutdownHook() method that is declared on the
ConfigurableApplicationContext interface, as the following example shows:
注册关闭钩子,请调用在 ConfigurableApplicationContext 接口上声明的 registerShutdownHook() 方法,如下例所示:
ApplicationContextAware andBeanNameAware 1.6.2.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.context.ApplicationContextAware 接口的对象实例时,实例将获得对该
ApplicationContext 的引用。以下列表显示了 ApplicationContextAware 接口的定义:
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.
因此,豆类可以通过 ApplicationContext 接口或通过将引用强制转换为该接口的已知子类(如
ConfigurableApplicationContext
,它提供了额外的功能)来编程式地操作创建它们的 ApplicationContext 。一个用途是编程式检索其他豆类。有时这种能力很有用。
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.
然而,通常情况下,你应该避免使用它,因为它将代码与 Spring 耦合,并且不符合控制反转(IoC)风格,其中协作者作为属性提供给
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 的引用的另一种选择。传统的 constructor 和 byType
自动装配模式(如《自动装配协作器》中所述)可以为构造函数参数或 setter 方法参数提供类型为 ApplicationContext
的依赖项。为了获得更多灵活性,包括自动装配字段和多个参数方法的能力,请使用基于注解的自动装配功能。如果这样做,当相关的字段、构造函数或方法带有
@Autowired 注解时, ApplicationContext 将自动装配到期望类型为 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 接口的定义:
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-method)之前被调用。
Aware Interfaces1.6.3. 其他 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:
除了之前讨论的 ApplicationContextAware 和 BeanNameAware ,Spring 提供了一系列 Aware 回调接口,允许 Bean
向容器表明它们需要特定的基础设施依赖。一般来说,名称表示依赖类型。下表总结了最重要的 Aware 接口:
Table 4. Aware interfaces 表 4. 意识界面
Name 姓名
Injected Dependency 注入依赖
Explained in… 解释在..
ApplicationContextAware
Declaring ApplicationContext. 声明 ApplicationContext 。
ApplicationContextAware and BeanNameAware ApplicationContextAware 和 BeanNameAware
ApplicationEventPublisherAware
Event publisher of the enclosing ApplicationContext.
事件发布者,封装的 ApplicationContext 。
Additional Capabilities of the ApplicationContext
附加功能
BeanClassLoaderAware
Class loader used to load the bean classes. 类加载器用于加载 bean 类。
BeanFactoryAware
Declaring BeanFactory. 声明 BeanFactory 。
The BeanFactory API BeanFactory API
BeanNameAware
Name of the declaring bean. 声明 Bean 的名称。
ApplicationContextAware and BeanNameAware ApplicationContextAware 和 BeanNameAware
LoadTimeWeaverAware
Defined weaver for processing class definition at load time. 定义在加载时处理类定义的织工。
Load-time Weaving with AspectJ in the Spring Framework Spring 框架中使用 AspectJ 进行加载时织入
MessageSourceAware
Configured strategy for resolving messages (with support for parametrization and internationalization). 配置了解决消息的策略(支持参数化和国际化)。
Additional Capabilities of the ApplicationContext
附加功能
NotificationPublisherAware
Spring JMX notification publisher. Spring JMX 通知发布者。
ResourceLoaderAware
Configured loader for low-level access to resources. 配置了用于资源低级访问的加载器。
ServletConfigAware
Current ServletConfig the container runs in. Valid only in a web-aware Spring ApplicationContext.
当前 ServletConfig 容器运行的位置。仅在具有网络意识的 Spring ApplicationContext 中有效。
ServletContextAware
Current ServletContext the container runs in. Valid only in a web-aware Spring ApplicationContext.
当前 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,并且不符合控制反转风格。因此,我们建议它们用于需要程序访问容器的基础设施 bean。