7.4.3 Using depends-on

If a bean is a dependency of another that usually means that one bean is set as a property of another. Typically you accomplish this with the <ref/> element in XML-based configuration metadata. However, sometimes dependencies between beans are less direct; for example, a static initializer in a class needs to be triggered, such as database driver registration. The depends-on attribute can explicitly force one or more beans to be initialized before the bean using this element is initialized. The following example uses the depends-on attribute to express a dependency on a single bean:

如果一个bean是另一个bean的依赖,通过就是说,一个bean被设置作为另一个bean的属性.通常你在基于XML配置元数据中通过使用 <ref/> 元素.然而,有时依赖在bean之间不是很直接;例如,一个静态初始化在一个类中需要被触发,例如数据库驱动注册.在这个使用这个 depends-on 元素的bean被初始化之前, depends-on 属性能够强迫一个或多个bean被初始化.下面的例子使用了这个 depends-on 属性去表达一个单例bean的一个依赖:

<bean id="beanOne" class="ExampleBean" depends-on="manager"/>
<bean id="manager" class="ManagerBean" />

To express a dependency on multiple beans, supply a list of bean names as the value of the depends-on attribute, with commas, whitespace and semicolons, used as valid delimiters:

为了表达依赖多个bean,提供一系列的bean名称作为 depends-on 属性的值,通过逗号,空格和分号作为有效分隔符:

<bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao">
    <property name="manager" ref="manager" />
</bean>

<bean id="manager" class="ManagerBean" />
<bean id="accountDao" class="x.y.jdbc.JdbcAccountDao" />

The depends-on attribute in the bean definition can specify both an initialization time dependency and, in the case of singleton beans only, a corresponding destroy time dependency. Dependent beans that define a depends-on relationship with a given bean are destroyed first, prior to the given bean itself being destroyed. Thus depends-on can also control shutdown order.

 depends-on 属性在bean定义中可以指定两个依赖的初始化时间,仅在单例bean中,指定两者依赖相应的销毁时间.通过给定bean定义了一个 depends-on 关系的依赖bean首先被销毁,在给定的bean本身被销毁之前.因此 depends-on 也可以控制结束顺序.

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/80885383