2013-01-07 102 views
7

我有三個類CircleBuilder,SquareBuilderTriangleBuilder實現了ShapeBuilder接口。用google-guice注入列表的最佳方式是什麼?

我需要初始化我的FormBuilder,特別是BuilderList(擴展List<ShapeBuilder>),每個類的一個實例使用google-guice。

什麼是最好的方法?

我瞭解供應商的方法和這樣的東西:

@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手動這違背了使用吉斯的目的(因爲FormBuilder是在頂部元件我對象圖)。

我很樂意能寫這樣的事:

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

任何想法?

回答

9

考慮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不僅會自動綁定所有綁定類型的提供者,還會注入任何方法中的每個參數。

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

注:multibinding需要另一個罐子 - >吉斯 - multibindings-3.0.jar –

0

我們可以做這樣的事情: -

@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); 
} 

在你FormBuilder類: -

class FormBuilder{ 
    List<ShapeBuilder> shapeBuilderList; 
    @Inject 
    public FormBuilder(@Named("Circle")ShapeBuilder circle, @Named("Triangle")ShapeBuilder triangle,@Named("Square")ShapeBuilder square){ 
     shapeBuilderList = new ArrayList<>(); 
     //add all of them 
     shapeBuilderList.add(circle); 
    } 
} 
相關問題