Guice辅助注射



我是Guice的新手,所以我正在尝试了解AssistEdinject。我的项目非常简单:

我想注入的类:

public class I1 {
}

辅助注入的课程:

public interface ICla {
}
public class Cla implements ICla{
    public Integer t;
    public I1 i;
    @Inject
    public Cla(Integer t, @Assisted I1 i) {
        this.t = t;
        this.i = i;
    }
}

工厂

public interface IClaFactory {
    Cla create(Integer t);
}

和主要类:

public class Main {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new Module());
        IClaFactory factory = injector.getInstance(IClaFactory.class);
    }
    private static class Module extends AbstractModule {
        protected void configure() {
            install(new FactoryModuleBuilder()
                .implement(ICla.class, Cla.class).build(IClaFactory.class));
        }
    }
}

但它仍然不起作用,我不明白,我在哪里错了?

Exception in thread "main" com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for ru.test.factory.I1 annotated with @com.google.inject.assistedinject.Assisted(value=) was bound.
  while locating ru.test.factory.I1 annotated with @com.google.inject.assistedinject.Assisted(value=)
    for parameter 1 at ru.test.factory.Cla.<init>(Cla.java:11)
  at ru.test.factory.IClaFactory.create(IClaFactory.java:1)
  at com.google.inject.assistedinject.FactoryProvider2.initialize(FactoryProvider2.java:660)
  at com.google.inject.assistedinject.FactoryModuleBuilder$1.configure(FactoryModuleBuilder.java:335) (via modules: ru.test.Main$Module -> com.google.inject.assistedinject.FactoryModuleBuilder$1)
2) Could not find a suitable constructor in java.lang.Integer. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
  at java.lang.Integer.class(Integer.java:52)
  while locating java.lang.Integer
    for parameter 0 at ru.test.factory.Cla.<init>(Cla.java:11)
  at ru.test.factory.IClaFactory.create(IClaFactory.java:1)
  at com.google.inject.assistedinject.FactoryProvider2.initialize(FactoryProvider2.java:660)
  at com.google.inject.assistedinject.FactoryModuleBuilder$1.configure(FactoryModuleBuilder.java:335) (via modules: ru.test.Main$Module -> com.google.inject.assistedinject.FactoryModuleBuilder$1)

您是 @Assisted -ing错误的参数:"辅助"参数是工厂接口中定义的参数。在这种情况下,是您的Integer,而不是您的I1

这将有效:

@Inject
public Cla(I1 i, @Assisted Integer t) {
    this.t = t;
    this.i = i;
}

相关内容

  • 没有找到相关文章

最新更新