vendredi 13 mars 2015

Why should we not use look up instead of dependency injection? [on hold]

For the stackoverflow moderators: just close this question. I have got already the answer.


Is there any good reason to not look up an object in application context instead of "suppose" a dependency was injected? Ex:



public Dependency getDependency(){
if (dependency == null){
dependency = (Dependency) applicationContext.getBean("dependency");
}
return dependency;
}


Debatable arguments


Polluting object with Spring specific object


Some people could complain that using application context will bind the implementation with Spring stuffs. BUT, it could be trivially solved creating a indirection to applicationContext. Ok... let me exemplify:



public Dependency getDependency(){
if (dependency == null){
dependency = (Dependency) serviceLocator.getBean("dependency");
}
return dependency;
}


Hard to change implementation


First, it (the dependency object) could be easily changed in application context. But, even easier a mock could be insert directly using the usual mutator:



public void setDependency(Dependency dep){
this.dependency = dep;
}


Historical question


Long time ago, everybody in Java world was using Service Locator (in a directory service by a technology called JNDI) to have a interchangeable object infrastructure. We could bind in the directory service three kind of objects: serializable data, reference or Dircontext. It would additionally allow you to look up objects in distributed environment.


Then, we have the Spring revolution and now DI (Dependency injection) is used most of the cases.


However, the service locator pattern was not prohibited by Spring. For instance, using ApplicationContext allow us to look up the beans in a service locator way. We could think that the Spring framework provides a big factory of objects with a centralized configuration, the dependency injection facility but also a directory of services that could be easily handle. The last part has been almost forgotten.


Related Question


Why is Spring's ApplicationContext.getBean considered bad?


I am not considering that because those answers although edifying , they are not enlightening the points raise above.


Aucun commentaire:

Enregistrer un commentaire