Search code examples
dependency-injectionjava-8picocontainer

Register a list of implementations with Pico Container


I have an interface

public interface IInterface{}

And I have a list of implementations of this interface:

public class MyClass1 implements IInterface{}
public class MyClass2 implements IInterface{}

What I'd like to do with Pico Container:

  1. Register all implementations of IInterface to be able to resolve them as a list:

    public class MyTest {
        public MyTest(IInterface[] list){}
    }
    
  2. And another option is to be able to register implementation with named key:

    container.addComponent(IInterface.class, MyClass1.class, "name1");
    container.addComponent(IInterface.class, MyClass2.class, "name2");
    

    to be able to do something like:

    container.getComponent(IInterface.class, "name2");
    

Is there built-in solution for at least 1st question?

UPD

  1. Found this implementation in Pico quite strange and not intuitive.

To be able to inject an array it's necessary:

container.addComponent(MyClass1.class);
container.addComponent(MyClass2.class);
container.addComponent(MyTest.class);
MyTest test = container.getComponent(MyTest.class);

This will inject an array of all implementations. But this behavior is very unclear and not intuitive. As for me it would be better to register pairs.


Solution

  • 1st part works exactly as you described. Just register any number of implementations in usual way, then they can be injected as an array (does not require any injection params) or collection. You can see example with array in sample project // ServerRegistrar, AppPico

    For 2nd part there're several built in solutions e.g. using named annotations (just like in Guice) which I personally disapprove. Or using injection parameters (which is close to your expectations). Or using some custom approach which I can explain in details, if you want.