首页 > 解决方案 > Guice - 绑定注解配置错误

问题描述

我有一个CustomInterface,它有两个实现类,即InterfaceImplA 和InterfaceImplB。我只是想将这两个注入到管理器类方法中各自的字段中,其中 implA 应该注入 InterfaceImplA 而 implB 应该注入 InterfaceImplB。

我有一个经理类定义为

    @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 {}

最后我的模块类将这些类绑定如下

    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

我很确定我在上面的绑定代码中遗漏了一些东西。任何帮助将不胜感激。

标签: javadependency-injectionguice

解决方案


我发现了问题。好像龙目岛

@RequiredArgsConstructor(onConstructor = @__(@Inject))

在 Manager 类上正在从生成的代码中删除注释 @interfaceAnnotationA 和 @interfaceAnnotationB。

我必须删除 @RequiredArgsConstructor 并手动编写构造函数,如下所示

    @Inject
    public CustomManager(@interfaceAnnotationA  CustomInterface implA,
                         @interfaceAnnotationB  CustomInterface implB) {
        this.implA = implA;
        this.implB = implB;
    }

我想知道是否有办法让 guice 绑定注释与 lombok @RequiredArgsConstructor 一起使用


推荐阅读