How to use Picocontainer Web?

255 views Asked by At

I'm trying to use Picocontainer Web (picocontainer-web-core-2.5.1.jar).

I have configured everything and I checked out that everything works just fine, until trying to retrieve anything from container... :p

I though I should use static method getRequestComponentForThread(Class type) from PicoServletContainerFilter class, which looks like this:

public static Object getRequestComponentForThread(Class type) {
        MutablePicoContainer requestContainer = ServletFilter.currentRequestContainer.get();
        MutablePicoContainer container = new DefaultPicoContainer(requestContainer);
        container.addComponent(type);
        return container.getComponent(type);
}

But as you can see, in that method, new instance of DefaultPicoContainer is created and type which I'm trying to retrieve is being registered.

  • if type is a Class - new instance is created and returned, instead of cached one from parent container...
  • if type is a Interface - runtime exception ("'ExampleInterface' is not instantiable") is being thrown, at 3rd line (addComponent).

And my question is: How to use this library? I was pretty sure that I understand it, but implementation of this one method blows my mind...

2

There are 2 answers

0
xeye On BEST ANSWER

Actually you should not use getComponent unless there's a special case. App/Session/Request containers are created for you when you add pico context listener to the web.xml. Just configure components for each scope and picocontainer will inject stuff automatically and instantiate components when needed. Also use Startable lifecycle interface.

0
kingsvid On

I figured out one acceptable solution - writing own version of org.picocontainer.web.PicoServletContainerFilter.ServletFilter - and adding one method:

public class MyComponentContainer extends PicoServletContainerFilter {

    /*
    code from original class PicoServletContainerFilter.ServletFilter
    [...]
    */

    public static <T> T getComponent(Class<T> clazz) {
        return (T) currentRequestContainer.get().getComponent(clazz);   
    }
}

I'm not sure if it's the best to do, but it work's fine for me. However, if you know better solution I'd be grateful for information :)