2

I am trying to use the picoContainer in my project. I know very little about it but want to give it a shot.

As I understand, I have to create a picoContainer and registercomponents with it. I did this

public static PicoContainer getPicoContainer(){
     final MutablePicoContainer pico = new DefaultPicoContainer();
     pico.registerComponentImplementation(X.class);
     pico.registerComponentImplementation(A.class);
     pico.registerComponentImplementation(C.class);
     pico.registerComponentImplementation(V.class);
     pico.registerComponentImplementation(T.class);
     pico.registerComponentImplementation(D.class);

     return pico;
}

Now my problem is that for any component to get the other component, it needs a handle on pico. To access any component it needs to do this

A juicer = pico.getComponent(A.class);

So, in the constructor for each of them, I need to pass in the pico object? I can easily replace this with a factory. What's the point then? I'm sure i'm missing something here. Would appreciate any help.

12rad
  • 829
  • 2
  • 13
  • 28
  • 1
    A component that requires another component in it's constructor should already get an instance of that component. http://picocontainer.codehaus.org/constructor-injection.html - Classes should not be responsible to create required other classes, they should get them injected. – zapl Feb 17 '14 at 23:51

1 Answers1

2

Common pattern is to have somewhere a factory for the main container. For stand-alone app it probably will be "public static void main()" entry point, for web app it will be front controller servlet or filter or context listener (pico has support class for listener case). So at the entry point you configure the container in a way you mentioned above "public static PicoContainer getPicoContainer()" then you need to pass control to an entry point in the container. The nice way is to have at least one container's component to implement lifecycle interface (http://picocontainer.codehaus.org/lifecycle.html) then you start() the container and have everything wired up. In normal case you should never access the container itself beside entry configuration and such things as special factories or transaction demarcation etc.

xeye
  • 1,250
  • 10
  • 15