Tue, 28 Dec 2004
As far as I know there is no simple way to use PicoContainer (tiny IoC framework) in servlet container environment for filters, servlets and so on... (this is also true for any managed object in non-IoC aware container)
The problem is that we cannot control instantiation of such objects -- it is hard coded into servlet engine. But we can of course execute dependecy lookup code in contructor itself (loosing any IoC abilities :/), or we can use AspectJ (or any other AOP framework) to decouple dependency lookup code from constructor. going futher we can use setter injection on our already instantiated object.
It sounds simple and (probably) logical but PicoContainer desn't support injection in already instantiated object 'out of the box' (or at last I couldn't find it). I have achieved this by hacking around SetterInjectionComponentAdapter and creating my own InstanceSetterInjectionAdapter. Resolving dependencies is now as easy as creating one simple aspect:
pointcut ReferenceServiceInitialization () : execution (public ReferenceService.new ());
after (): ReferenceServiceInitialization () {
MutablePicoContainer picoContainer = getPicoContainer ();
PicoUtils.resolveDependencies (picoContainer, thisJoinPoint.getThis ());
}
@injectDeps (container="root") public class SomeFilter implements ServletFilter {
...
}
An example is available as compressed eclipse project, just import it into your workspace and take a look. It doesn't depend on servlet/or-something container it is just uses this IoC hack to show this basic idea. (you must have AJDT installed because it is AspectJ project)
update:- 01-jan: colorized source code with java2html.
