1.6. Customizing the Nature of a Bean

上一节 1.5. Bean Scopes

目录

下一节 1.7. Bean Definition Inheritance

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框架提供了大量的接口,您可以使用它们来定制bean的特性。
本节将它们归类如下:

  • Lifecycle Callbacks
  • ApplicationContextAware and BeanNameAware
  • Other Aware Interfaces
* 生命周期回调
* ApplicationContextAware and BeanNameAware
* 其他 Aware 接口
1.6.1. Lifecycle Callbacks
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在初始化和
销毁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注释,但是您仍然希望消除耦合,请考虑bean definition 
元数据中的 init-method和destroy-method 。

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管理的对象还可以实现生命周期接口,
以便这些对象可以参与启动和关闭过程,这是由容器自己的生命周期驱动的。

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上
设置了所有必要的属性之后执行初始化工作。
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在
包含它的容器被销毁时获得回调。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 . With Java configuration, you can use the destroyMethod attribute of @Bean. See Receiving Lifecycle Callbacks. Consider the following definition:

我们建议您不要使用一次性bean回调接口,因为它不必要地将代码与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 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 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 definition配置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 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-in-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 element.

您可以用类似的方式(在XML中)配置销毁方法回调,方法是使用顶层元素
<beans/>default-destroy-method属性。

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 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:

结合生命周期机制
从spring2.5开始,控制bean生命周期行为有三种选择:

  • 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.
* 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 executed 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 executed 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
销毁方法的调用顺序相同:
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本身就是生命周期接口的扩展。
它还添加了另外两个方法,用于对刷新和关闭上下文做出反应。

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.

请注意常规的org.springframework.context.Lifecycle接口
是显式启动和停止通知的普通规定,并不意味着在上下文刷新时自动启动。
对于特定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 aborted refresh attempts, only destroy methods are called.

另外,请注意,停止通知不能保证在销毁之前发出。
在常规关闭时,所有生命周期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接口定义了另一个选项,
即在其超接口Phase上定义的getPhase()方法。
下面的清单显示了阶段性接口的定义:

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.

开始时,phase最低值的对象先开始。当停止时,按相反的顺序执行。
因此,实现SmartLifecycle并其getPhase()方法返回 Integer.MIN_VALUE将首先开始,
最后停止。
在取值范围的另一端, phase的值 Integer.MAX_VALUE表示应该最后启动
并首先停止该对象(可能是因为它依赖于正在运行的其他进程)。
当考虑phase值时,同样重要的是要知道对于任何没有实现SmartLifecycle的
“正常”生命周期对象,其默认的phase是0。
因此,任何phase的负数都表示一个对象应该在那些标准组件之前开始
(并在它们之后停止)。对于任何phase的正数,情况正好相反。

[WORD]
spectrum 
英 /ˈspektrəm/  美 /ˈspektrəm/  全球(英国)  
例句 百科n. 光谱;频谱;范围;余象

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会等待每个阶段中对象组调用该回调的超时值。
每个phase的默认超时时间为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的另一个特性。
当上下文被刷新时(在所有对象被实例化和初始化之后),回调被调用。
这时,默认的 lifecycle processor 会检查每个SmartLifecycle对象的isAutoStartup()
方法返回的布尔值。
如果为真,则在该点启动该对象,而不是等待上下文或其自己的start()方法的显式调用
(与 context 刷新不同,对于标准 context 实现,context 启动不会自动发生)。
如上所述,phase 值和任何“依赖”关系决定启动顺序。

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 IoC容器
本节仅适用于非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注册一个关闭hook。
这样做可以确保优雅地关闭,并调用 singleton bean上的相关销毁方法,
从而释放所有资源。
您仍然必须正确配置和实现这些销毁回调。

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

要注册关闭hook,调用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

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。
这些附加特性在 Additional Capabilities of the 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引用的另一种选择。
传统的构造函数和byType自动装配模式(如在Autowiring Collaborators 章节所描述的)
可以分别为构造函数参数或setter方法参数提供类型ApplicationContext的依赖关系。
为了获得更大的灵活性,包括自动装配字段和多个参数方法的能力,
可以使用基于注释的自动装配特性。
如果你这样做了,ApplicationContext就会自动生成一个字段、构造函数参数或方法参数,
如果有问题的字段、构造函数或方法带有@Autowired注解,那么这些参数期望得到
ApplicationContext类型。
更多信息,请参见 章节 - Using @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-method)之前调用回调。

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接口:

#####Table 4. Aware interfaces

NameInjected DependencyExplained in…
ApplicationContextAwareDeclaring ApplicationContext.ApplicationContextAware and BeanNameAware
ApplicationEventPublisherAwareEvent publisher of the enclosing ApplicationContext.Additional Capabilities of the ApplicationContext
BeanClassLoaderAwareClass loader used to load the bean classes.Instantiating Beans
BeanFactoryAwareDeclaring BeanFactory.ApplicationContextAware and BeanNameAware
BeanNameAwareName of the declaring bean.ApplicationContextAware and BeanNameAware
BootstrapContextAwareResource adapter BootstrapContext the container runs in. Typically available only in JCA-aware ApplicationContext instances.JCA CCI
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.NotificationsResourceLoaderAwareConfigured loader for low-level access to resources.Resources
ServletConfigAwareCurrent ServletConfig the container runs in. Valid only in a web-aware Spring ApplicationContext.Spring MVC
ServletContextAwareCurrent 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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值