Picocontainer:注入多个相同类型的对象

时间:2018-10-05 10:56:54

标签: java dependency-injection picocontainer

我正在使用DI并具有以下内容

  public DoSomethingWithUsers(User user1, User user2){
      this.user1 = user1;
      this.user2 = user2;
  }

请注意,同一类型将被注入两次。

在进行编码/测试时,我注意到在user1和user2上运行的所有方法都在影响user1。

是否可以使用picocontainer注入多个相同类型的对象,并使它们成为预期的“独立”对象?或者,是否存在允许这种行为的其他DI包?

thnx

1 个答案:

答案 0 :(得分:0)

您可以在pico中使用以下选项:

1)您可以注入诸如DoSomethingWithUsers(User[] users)之类的用户集合或数组 并且将使用容器中所有可用的User实例填充该实例,但不能保证顺序,因此无论如何都要执行组操作很方便。

2)使用ComponentParameter提示组件键

MutablePicoContainer pico = new DefaultPicoContainer();
pico.addComponent("user1", userInstance1);
pico.addComponent("user2", userInstance2);
pico.addComponent(DoSomethingWithUsers.class, DoSomethingWithUsers.class, 
    new Parameter[]{ new ComponentParameter("user1"), new ComponentParameter("user2")}); 

3)您可以像以下示例一样利用参数名称:http://picocontainer.com/parameter-names.html

此处有更多示例:http://picocontainer.com/arrays-collections-and-maps.html

相关问题