2014-04-27 230 views
0

依赖注入(DI)背后的基本原理是对象只能通过构造函数参数,工厂方法的参数或者设置的属性来定义它们的依赖关系(也就是说它们所处理的其他对象)对象实例在构造或从工厂方法返回后。注入依赖关系

这里究竟是什么工厂方法?

回答

1

看看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作为参数传递给工厂方法来实现的。

0

工厂方法是对象创建的设计模式。 Factory Method定义了一个创建对象的接口,但是可以让子类决定实例化哪些类。欲了解更多信息,你可以阅读here