This post originated from an RSS feed registered with Java Buzz
by Adam Kruszewski.
Original Post: PicoContainer, AOP and containers you don't possess.
Feed Title: Adam Kruszewski :: WebLog();
Feed URL: http://adam.kruszewski.name/blojsom/blog/adam.kruszewski/?flavor=rss2
Feed Description: Thoughts about linux, open source, programming, ...
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:
It will be more easier when AspectJ will have full support for J2SE5.0 features. Then it will be possible to write our classes as:
@injectDeps (container="root") public class SomeFilter implements ServletFilter {
...
}
and leave rest to our little aspect ;)
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)