Difference between Dependency Injection and Factory in Spring

Dependency Injection

We learn what is Dependency Injection in last article. Now take a look on Factory In Spring FW.

Factory

Factory and Dependency Injection may look related but we can understand that they are different. If we use a factory Design Pattern the dependent class has the responsibility of creating the instance but the core of dependency injection is separating that responsibility to external component.
 

For Example (Factory):

Class A
{
private B ob;
 
public void Method()
{
.....;
.....;
 
this.ob=MyObjectFactory.get();
 
....;
....;
}//method
} //class

In Dependency Injection:

Class A
{
private B ob;
 
public void Method(B ob)
{
....;
this.ob=ob;
....;

}//method
} //class
 
 
 


 

0 comments:

Post a Comment