Friday, January 16, 2015

Middle Ground between 'Newable' and 'Injectable'?

As noted previously, Misko Hevery asserts that every objects should be either an "injectable" or a "newable."

The question is: why does then Spring support prototype scoped objects which can be injected with well injectables? The condensed and recently supported alternative (through this initiative) to creating a prototype scope object -- which requires access to the ApplicationContext through ApplicationContextAware or BeanFactoryaware (not good* because it becomes a Service Locator "DI Catch 22") -- i.e. the @Lookup or lookup-method with parameters supported is really just syntactic sugar for a prototype scope object, IMO.

On the other hand, the fact that Spring does the wiring under the covers may make @Lookup-with-parameters okay. However, if one tried to do the same in code it would probably violate Misko's rule stating you should not inject an injectable into a newable, where the newable is the prototyped scoped object.


*Note: it may be more nuanced than black and white whether usage of an injected ApplicationContext is or is not good IoC. e.g. see comments by Alex Worden regarding enabling a sort of polymorphism where you "dynamically create new bean instances based on a bean name that is unknown at compile time but matches one of the implementations defined in my spring.xml file" - http://stackoverflow.com/questions/812415/why-is-springs-applicationcontext-getbean-considered-bad this might be a valid use of 'ContextAware. Commenters note that this is not really IoC but rather ordinary factory or Service Locator but pap notes that "Spring is about more than just IoC."

Similar question raised here.

Found this problem is similar to the question of how to do DI and the Command Pattern at the same time. Turns out they may be incompatible. see and see

No comments:

Post a Comment