【发布时间】:2014-06-12 18:10:32
【问题描述】:
依赖注入 (DI) 背后的基本原理是对象仅通过构造函数参数、工厂方法的参数或在对象实例上设置的属性来定义它们的依赖关系(即与它们一起工作的其他对象)在它被构造或从工厂方法返回之后。
这个工厂方法到底是什么?
【问题讨论】:
标签: spring
依赖注入 (DI) 背后的基本原理是对象仅通过构造函数参数、工厂方法的参数或在对象实例上设置的属性来定义它们的依赖关系(即与它们一起工作的其他对象)在它被构造或从工厂方法返回之后。
这个工厂方法到底是什么?
【问题讨论】:
标签: spring
看看last example in this Spring reference documentation section。
这是示例:
<bean id="exampleBean" class="examples.ExampleBean" factory-method="createInstance">
<constructor-arg ref="anotherExampleBean"/>
<constructor-arg ref="yetAnotherBean"/>
<constructor-arg value="1"/>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
ExampleBean 类:
public class ExampleBean {
// a private constructor
private ExampleBean(...) {
...
}
// a static factory method; the arguments to this method can be
// considered the dependencies of the bean that is returned,
// regardless of how those arguments are actually used.
public static ExampleBean createInstance (
AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
ExampleBean eb = new ExampleBean (...);
// some other operations...
return eb;
}
}
因此,一个 bean 的实例是在同一个 bean 中使用工厂方法创建的。依赖注入是通过将其他bean作为参数传递给工厂方法来实现的。
【讨论】:
工厂方法是一种用于对象创建的设计模式。工厂方法定义了一个用于创建对象的接口,但让子类决定要实例化哪些类。更多信息可以阅读here。
【讨论】: