Guice Assisted Inject被忽略了吗?

时间:2014-03-21 20:23:39

标签: java algorithm guice guice-3

我在Google Guice中使用AssistedInject安装了一个工厂,但是我收到以下错误(我正在使用JUnit运行单元测试):

com.google.inject.CreationException: Guice creation errors:

1) No implementation for clusterestimator.OptimalClusterEstimatorFactory was bound.
  while locating clusterestimator.OptimalClusterEstimatorFactory
    for parameter 0 at com.myfeed.algorithm.clusterer.tree.fca.BasicFCATreeFactory.<init>(BasicFCATreeFactory.java:16)
  FCAModule.configure(FCAModule.java:29)

即使我从模块中省略了install(new Factory...);行,这个错误也是一样的,这让我觉得该行被忽略了。

以下是模块代码

public class FCAModule extends AbstractModule {

    @Override
    protected void configure() {
        install(new FactoryModuleBuilder() // <-- Factory line that's not working
            .implement(OptimalClusterEstimator.class, FCAOptimalClusterEstimator.class)
            .build(OptimalClusterEstimatorFactory.class));
        bind(ValueWell.class).to(MapBackedValueWell.class).asEagerSingleton();
        bind(FCATreeFactory.class).to(BasicFCATreeFactory.class).asEagerSingleton();
        bind(ItemFactory.class).to(MapBackedItemFactory.class).asEagerSingleton();
        bind(ClustererFactory.class).asEagerSingleton();
        bind(ClusterFactory.class).to(MemoryBackedClusterFactory.class).asEagerSingleton();
    }

}

以下是工厂界面

public interface OptimalClusterEstimatorFactory {
    public <T> OptimalClusterEstimator createFCA(int kValue, ItemPointReducer<T> pointReducer);
}

以下是FCAOPtimalClusterEstimator的构造函数

@AssistedInject
public FCAOptimalClusterEstimator(@Assisted int kValue, @Assisted ItemPointReducer<T> pointReducer) {
    this.kValue = kValue;
    this.pointReducer = pointReducer;
}

这是BasicFCATreeFactory 的构造函数,是第一个调用其他工厂的东西。请注意,此工厂不是使用AssistedInject创建的,因为它使用泛型。

@Inject
public BasicFCATreeFactory(OptimalClusterEstimatorFactory optimalClusterEstimatorFactory, ClustererFactory clustererFactory, ClusterFactory clusterFactory) {
    this.optimalClusterEstimatorFactory = optimalClusterEstimatorFactory;
    this.clustererFactory = clustererFactory;
    this.clusterFactory = clusterFactory;
}

2 个答案:

答案 0 :(得分:2)

由于某些未知原因,从工厂界面中删除<T>通用部件解决了这个问题。我之前遇到过泛型和Guice的问题,所以也许这只是因为类型擦除而导致的另一个怪癖。

所以工厂界面现在是:

public interface OptimalClusterEstimatorFactory {
    public OptimalClusterEstimator createFCA(int kValue, ItemPointReducer pointReducer);
}

答案 1 :(得分:2)

Guice辅助注射对仿制药效果不佳。如果您想使用泛型,那么您已经编写了自己的工厂。