使用google-guice注入列表的最佳方法是什么?

时间:2013-01-07 20:41:49

标签: java dependency-injection guice

我有三个课程CircleBuilderSquareBuilderTriangleBuilder实施ShapeBuilder界面。

我需要使用google-guice初始化我的FormBuilder,特别是BuilderList(扩展List<ShapeBuilder>),每个类的一个实例。

最好的方法是什么?

我知道提供者方法和类似的东西:

@Provides
FormBuilder provideFormBuilder() {
    DatabaseTransactionLog instance = new FormBuilder ( <numerous parameters> );

    ShapeBuilder builder = null ; 
    builder = new CircleBuilder( <numerous parameters> ) ;  
    instance.addBuilder( builder ) ;

    builder = new SquareBuilder( <numerous parameters> ) ;  
    instance.addBuilder( builder ) ;

    // And so on

    return instance;
}

但这意味着我必须手动创建FormBuilder,这会违背使用guice的目的(因为FormBuilder是对象图中的顶部元素)。

我希望能够写出这样的东西:

bind(BuilderList.class).to(CircleBuilder.class);
bind(BuilderList.class).to(TriangleBuilder.class);
bind(BuilderList.class).to(SquareBuilder.class);

有什么想法吗?

2 个答案:

答案 0 :(得分:13)

考虑Multibindings,它会像你的代码片段一样收集绑定。 Multibinder没有提供列表,因为Multibinder设计用于绑定多个模块中的相同集合,Multibinder列表的元素顺序取决于模块评估的顺序。

Multibinder<ShapeBuilder> shapeBinder =
    Multibinder.newSetBinder(binder(), ShapeBuilder.class);
shapeBinder.addBinding().to(CircleBuilder.class);
shapeBinder.addBinding().to(TriangleBuilder.class);
shapeBinder.addBinding().to(SquareBuilder.class);

// Now you can inject Set<ShapeBuilder>.

或者,your @Provides method可以接受参数(例如CircleBuilderProvider<CircleBuilder>),这样您就可以让Guice创建除List本身之外的所有内容。 Guice不仅会自动绑定所有绑定类型的提供者,而且还会在任何@Provides方法中注入每个参数。

@Provides List<ShapeBuilder> provideShapeBuilders(
    CircleBuilder circleBuilder,
    SquareBuilder squareBuilder,
    TriangleBuilder triangleBuilder,
    Provider<TrapezoidBuilder> trapezoidBuilderProvider) {
  return new ArrayList<ShapeBuilder>(
      circleBuilder,
      squareBuilder,
      triangleBuilder,
      trapezoidBuilderProvider.get(),
      trapezoidBuilderProvider.get());
}

答案 1 :(得分:1)

我们可以这样做: -

def solution(A):
    l=len(A)
    for i in range(0,l):
        lnum=0                   #reset the sum of left to zero for every index
        rnum=0                   #      ""         right         ""
        for numl in range(0,i):         #sum up all values on left indices
            lnum+=A[numl]
        for numr in range(i+1,l):       #sum up all values on the right indices
            rnum+=A[numr]
        if lnum==rnum:                  #if the sum of left is equal to right...
            return i                    #return the index of equilibrium
        else:
            pass
    return -1 #no equilibrium!

在您的FormBuilder类中: -

@Override
protected void configure() {
    bind(ShapeBuilder.class).annotatedWith(Names.named("Circle")).to(CircleBuilder.class);
    bind(ShapeBuilder.class).annotatedWith(Names.named("Triangle")).to(TriangleBuilder.class);
    bind(ShapeBuilder.class).annotatedWith(Names.named("Square")).to(SquareBuilder.class);
}