使用@Singleton注释时,Dagger生成的代码编译失败

时间:2019-04-05 13:55:23

标签: dependency-injection singleton dagger-2 dagger

我正在使用Dagger - 2.6,并且具有以下课程。

public class Trigger {

    public static JSONObject triggerLambda(JSONObject jsonObject) {
        DataTransformerComponent daggerDataTransformerComponent =  DaggerDataTransformerComponent.create();
        return daggerDataTransformerComponent.getHandler().handle(jsonObject);

    }

}

数据处理程序类:

public class DataHandler {


    private static final Logger LOGGER = Logger.getLogger(DataHandler.class.getName());


    private A a;


    @Inject
    public DataHandler(A a) {
        this.a = a;
    }

    public JSONObject handle(JSONObject input) {
        LOGGER.info("Json input received - " + input.toString());
        return a.executeTransformation(input);
    }

}

和依赖项:

public class A {

    @Inject
    public A() {
    }

    public JSONObject executeTransformation(JSONObject jsonObject) {
        System.out.println("a");
        return null;
    }
}

我的组件类如下:

@Component
public interface DataTransformerComponent {

    DataHandler getHandler();
}

当我编译上面的代码时,它运行得很好。

现在我想将我的依赖项设为@Singleton。 因此,我如下更改了我的依赖项类和组件类:

@Singleton
@Component
public interface DataTransformerComponent {

    DataHandler getHandler();
}

依赖类:

@Singleton
public class A {

    @Inject
    public A() {
    }

    public JSONObject executeTransformation(JSONObject jsonObject) {
        System.out.println("a");
        return null;
    }
}

但是现在生成的组件显示编译错误,提示:

A_Factory未找到,并且在initialize()方法中失败。

DaggerDataTransformerComponent:

@Generated(
  value = "dagger.internal.codegen.ComponentProcessor",
  comments = "https://google.github.io/dagger"
)
public final class DaggerDataTransformerComponent implements DataTransformerComponent {
  private Provider<A> aProvider;

  private Provider<DataHandler> dataHandlerProvider;

  private DaggerDataTransformerComponent(Builder builder) {
    assert builder != null;
    initialize(builder);
  }

  public static Builder builder() {
    return new Builder();
  }

  public static DataTransformerComponent create() {
    return builder().build();
  }

  @SuppressWarnings("unchecked")
  private void initialize(final Builder builder) {

    this.aProvider = DoubleCheck.provider(A_Factory.create());

    this.dataHandlerProvider = DataHandler_Factory.create(aProvider);
  }

  @Override
  public DataHandler getHandler() {
    return dataHandlerProvider.get();
  }

  public static final class Builder {
    private Builder() {}

    public DataTransformerComponent build() {
      return new DaggerDataTransformerComponent(this);
    }
  }
}

当我使用@Singleton注释时,我无法弄清楚为什么它不创建_factory类。

1 个答案:

答案 0 :(得分:-2)

只需使用常规的JavaScript + node.js,它会简单得多