[英]Guice - Binding annotation configuration error
我有一個CustomInterface,它有兩個實現類,即InterfaceImplA 和InterfaceImplB。 我只是想在管理器 class 方法中將這兩個注入各自的字段,其中 implA 應該注入 InterfaceImplA 而 implB 應該注入 InterfaceImplB。
我有一個經理 class 定義為
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class CustomManager {
private @NonNull
@interfaceAnnotationA
final CustomInterface implA;
private @NonNull
@interfaceAnnotationB
final CustomInterface implB;
}
其中 CustomInterface 是一個包含兩個方法的接口。 我為兩個 Impl 類分別定義了綁定注釋,如下所示
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface interfaceAnnotationA {}
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface interfaceAnnotationB {}
最后我的模塊 class 將這些類綁定如下
public class CustomModule extends AbstractModule {
@Override
protected void configure() {
bind(CustomInterface.class).
annotatedWith(interfaceAnnotationA.class).to(InterfaceImplA.class);
bind(CustomInterface.class).
annotatedWith(interfaceAnnotationB.class).to(InterfaceImplB.class);
}
}
但是在運行時我得到如下錯誤
com.google.inject.ConfigurationException: Guice configuration errors:
1) No implementation for com.custom.CustomInterface was bound.
while locating com.custom.CustomInterface
for parameter 2 at com.custom.manager.CustomManager.<init>(CustomManager.java:111)
while locating com.custom.manager.CustomManager
for parameter 0 at com.custom.Activity.<init>(Activity.java:44)
while locating com.custom.Activity
1) No implementation for com.custom.CustomInterface was bound.
while locating com.custom.CustomInterface
for parameter 3 at com.custom.manager.CustomManager.<init>(CustomManager.java:111)
while locating com.custom.manager.CustomManager
for parameter 0 at com.custom.Activity.<init>(Activity.java:44)
while locating com.custom.Activity
2 errors
我很確定我在上面的綁定代碼中遺漏了一些東西。 任何幫助將不勝感激。
您正在綁定類型,但沒有實現。
您還可以通過@Provides
方法提供實現:
@Provides interfaceImplA provideInterffaceImplA() { ... }
或者通過模塊內的顯式綁定:
bind(interfaceImplA.class).toInstance(...);
// Or
bind(interfaceImplA.class).toProvider(...);
// Etc.
我發現了問題。 好像龍目島
@RequiredArgsConstructor(onConstructor = @__(@Inject))
在 Manager class 上,正在從生成的代碼中刪除注釋 @interfaceAnnotationA 和 @interfaceAnnotationB。
我必須刪除 @RequiredArgsConstructor 並手動編寫構造函數,如下所示
@Inject
public CustomManager(@interfaceAnnotationA CustomInterface implA,
@interfaceAnnotationB CustomInterface implB) {
this.implA = implA;
this.implB = implB;
}
我想知道是否有辦法讓 guice 綁定注釋與 lombok @RequiredArgsConstructor 一起使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.