【问题标题】:Guice- Unable to create InjectionGuice-无法创建注入
【发布时间】:2019-03-07 14:38:40
【问题描述】:

我正在使用 Guice 进行依赖注入,但在我的特定用例中,它给了我这个错误:

类必须有一个(且只有一个)用@Inject 注释的构造函数或一个非私有的零参数构造函数

我在这方面花了很多时间,但我仍然无法理解为什么它不能注入依赖项。有谁可以看看吗?

我的班级结构如下:

interface A {
}

B 类实现 A

Class B implements A {

  @Inject
  B(String para1, MyClass B) {
     // do something
  }

}

Guice 模块如下:

@AllArgsConstructor
public class GuiceModule extends AbstractModule {

@Override
protected void configure() {

    bind(A.class).to(B.class);

}

@Provides
public MyClass provideMyClass() {
    return new MyClass();
}


@Provides
public String provideString() {
    return "string";
}
}

在我正在做的其他课程中:

@Inject A a;

【问题讨论】:

  • 我尝试从 main 方法运行您的代码:A a = Guice.createInjector(new GuiceModule())(A.class); 一切正常。也许问题出在课堂上,您要在哪里注入A?你也可以提供这个类的代码吗?

标签: java dependency-injection guice


【解决方案1】:

你的构造函数应该是公开的,这样 guice 可以看到它并注入它。

这里是guice docs的一些参考

Class B implements A {

  @Inject
  ***public***  B(String para1, MyClass B) {
     // do something
  }
}

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多