简体   繁体   中英

how to `getInstance` with annotation using guice injector?

I'm using a FileHandler class that gets a File as a ctor parameter.

I want to use it with 2 different File s.

How can configure the injector to inject a different File each time?

Like getInstance with annoation that will return the desired concrete instance?

Annotation wouldn't help here as If I put it in the ctor, there will still be one annotation for all the usages of this ctor.

public class StringFileWriter implements IResponsesStorage {

    File file;

    @Inject
    @Singleton
    public StringFileWriter(@myAnnotation File file) {
        this.file = file;
    }

and

public class MainModule extends AbstractModule {

    @Override
    protected void configure() {

        File resultBaselineFile = new File(Constants.RESULTS_BASELINE_FILE);
        bind(File.class).annotatedWith(ResultBaselineFile.class).toInstance(resultBaselineFile);

        File logLatencyFile = new File(Constants.LATENCY_FILE);
        bind(File.class).annotatedWith(LatencyLogFile.class).toInstance(logLatencyFile);

edit

the main code calls 2 repositories: one for log files, second for result files. Each repository has it's own file handler. That's the problem

This is a variation on the so-called "robot legs" problem . As the comment above asks, the right solution really depends on where the decision is made.

Here's how I would solve this problem in this case:

public final class StringFileWriter implements IResponsesStorage {
  private final File file;

  // Note: constructor is not annotated with @Inject
  StringFileWriter(File file) {
    this.file = file;
  }

  // ...

}

public final class StringFileWriterModule extends AbstractModule {
  @Override protected void configure() {}

  @Provides
  @Singleton
  @ResultBaselineFile
  StringFileWriter provideResultBaselineFileWriter(
      @ResultBaselineFile File resultBaselineFile) {
    return new StringFileWriter(resultBaselineFile);
  }

  @Provides
  @Singleton
  @LatencyLogFile
  StringFileWriter provideLatencyLogFileWriter(
      @LatencyLogFile File latencyLogFile) {
    return new StringFileWriter(latencyLogFile);
  }
}

And then at the point of injection you would choose which StringFileWriter you wanted:

final class MyWorkerClass {
  private final StringFileWriter resultBaselineFileWriter;

  @Inject MyWorkerClass(@ResultBaselineFile StringFileWriter writer) {
    resultBaselineFileWriter = writer;
  }

  // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM