Reputation: 225
The basic principle behind Dependency Injection (DI) is that objects define their dependencies (that is to say the other objects they work with) only through constructor arguments, arguments to a factory method, or properties which are set on the object instance after it has been constructed or returned from a factory method.
Here what exactly is this factory method?
Upvotes: 0
Views: 203
Reputation: 52368
Take a look at the last example in this Spring reference documentation section.
This is the sample:
<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 class:
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;
}
}
So, an instance of a bean is created using a factory-method inside the same bean. And the dependency injection is achieved by passing other beans as arguments to the factory-method.
Upvotes: 1
Reputation: 2739
Factory Method is a design pattern for object creation. The Factory Method defines an interface for creating objects, but lets subclasses decide which classes to instantiate. For more information you can read here.
Upvotes: 0