Java Guice - 为特定实例使用注入?

时间:2013-12-23 18:45:36

标签: java dependency-injection guice

我不明白如何在Guice中使用注入特定实例。我试过这个:

@Inject(optional=true)
    public void setCarpenter(@Named("setCarpenter") Carpenter carpenter){
        System.out.println("Assigned carpenter for Table");
        this.carpenter = carpenter;
    }


bind(Table.class).annotatedWith(Names.named("table1")).toInstance(new Table(4, new Metal()));
bind(Table.class).annotatedWith(Names.named("table2")).toInstance(table);
bind(Carpenter.class).annotatedWith(Names.named("setCarpenter")).toInstance(new Carpenter());

它对两个表实例都使用setCarpenter。如何指定设置为特定实例?

1 个答案:

答案 0 :(得分:1)

我认为你可能正在寻找“机器人腿”问题的解决方案。

有关详细信息,请参阅维基here