【问题标题】:Guice: cannot inject assisted List<Long>Guice:无法注入辅助 List<Long>
【发布时间】:2025-11-28 13:30:02
【问题描述】:

我刚开始学习如何使用 Guice,但在尝试配置辅助注射时遇到了一些问题。我有如下界面:

public interface Individual extends Comparable<Individual>, Iterable<Long>{ ... }

它将由工厂创建。构造函数必须接收一个长列表:

public interface IndividualFactory {
    public Individual createIndividual(List<Long> chromossomes);
}

实现类有一个@Assisted参数来接收列表:

public class IndividualImpl implements Individual {
@Inject
public IndividualImpl(
    ConfigurationService configurationService,
    RandomService randomService,
    FitnessCalculatorService fitnessService,
    @Assisted List<Long> chromossomes
    ) { ... } 

最后,这是我的模块类:

public class SimpleModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Individual.class).to(IndividualImpl.class);
        install(new FactoryModuleBuilder().implement(Individual.class,
            IndividualImpl.class).build(IndividualFactory.class));
}

问题是我运行项目时显示这个错误:

1) No implementation for java.util.ArrayList<java.lang.Long> annotated with @com.google.inject.assistedinject.Assisted(value=) was bound.
  while locating java.util.ArrayList<java.lang.Long> annotated with @com.google.inject.assistedinject.Assisted(value=)
    for parameter 3 at implementation.entities.IndividualImpl.<init>(IndividualImpl.java:25)
  at SimpleModule.configure(SimpleModule.java:36)

如果我只是删除辅助参数(不仅是注释,还有参数本身)一切正常。我无法弄清楚我做错了什么。我遵循了我找到的所有 Guice 教程,但找不到使用 List; 的辅助参数示例;但是,即使我将此参数更改为整数,例如,我也会收到相同的错误。

【问题讨论】:

    标签: java dependency-injection guice guice-3


    【解决方案1】:

    删除:

    bind(Individual.class).to(IndividualImpl.class);
    

    使用您指定的绑定,以将 IndividualImpl 用于 @Inject Individual。这是没有意义的,因为您不会在代码中的任何地方@Inject Individual。您将改为 @Inject IndividualFactory。

    什么是远程可能的

    bind(Individual.class).toProvider(BlowUpWithUseFactoryExceptionProvider.class);
    

    但这样做是没有意义的,因为默认行为是相似的。

    我可以建议:

    Iterable<Long> -> DnaContaining
    List<Long> -> DnaMaterial
    

    【讨论】:

    • 这完全有道理。我以前试过这个,但做错了什么,无法确定是什么。现在它刚刚奏效了。按照你的建议,我很喜欢。将不得不更改代码中的某些内容,但我一定会这样做。