Saturday, February 21, 2009

Constructor dependency injection vs setter dependency injection

Hi ,

As per dependency injection we are having 2 popluar dependency injections as setter dependecy injection,constructor dependency injection.

setter dependency injection: In this injection we will inject everything as setter methods.
for example setEmpName(). etc .

constructor injection: In this injection we will inject everthing as constructor . for example we are having class Employee . then Employee(Arguments) construction can intialize itself .


Now which one is good ? It dependens on appliation. But i prefer constructor injection. Reason is constructor injection follows order , means there is very less number of chances for ambigity .

Let us assume that we are having 3 classes or beans with in our appliaction .

for ex : Employee ,dept ,school

so 3 of them are having same method name as "Name" describing as Employee name,dept name,school name etc..

so when ever you are applying setter injection as setName() there is chance for container to go wrong to different bean as cyclic error often some times.

but when ever you are using or calling constructor injection u have to call Employee(),dept(),school() respectively. one more point is it will follow order ,if it fails it throws error.

for example you are having certain classes like

y1 y=new y1();
k1 k =new k1(y);

through our constructor injection

H h=new H(y,k); // Here if it fails in any no of arguments code willn't compile at all .

Happy Sivarathri bye :_)

No comments: