5

注釈を導入したり、文字列キー名を使用したりせずに、次のことを実現したいと考えていGuiceます。また、 ExecutorService をアプリ全体のシングルトンにして、 だけでなく、他のクラスに注入する可能性があるためMyService、 とそのバインディングに 3 番目のプライベート モジュールを導入するExecutorServiceことは理想的とは言えません。MyServiceMyOtherService

public class Main {
  public static void main(String[] args) {
    final Injector injector = Guice.createInjector(new MyAppModule());
    final MyService service = injector.getInstance(MyService.class);
    service.printInternals();
    // Ideally this would print something like:
    // My Executor: ExecutorImplClass@1
    // Red Executor: ExecutorImplClass@2
    // Blue Executor: ExecutorImplClass@3
  }
}

public class MyAppModule extends PrivateModule {
  @Override
  protected void configure() {
    install(new RedModule());
    install(new BlueModule());
    bind(ExecutorService.class).toInstance(Executors.newSingleThreadExecutor());
    bind(MyService.class).to(MyServiceImpl.class);
    expose(MyService.class);
  }
}

public class BlueModule extends PrivateModule {
  @Override
  protected void configure() {
    bind(ExecutorService.class).toInstance(Executors.newSingleThreadExecutor());
    bind(BlueService.class).to(BlueServiceImpl.class);
    expose(BlueService.class);
  }
}

public interface BlueService {
  void printInternals();
}

class BlueServiceImpl implements BlueService {
  private final ExecutorService executor;

  @Inject
  BlueServiceImpl(final ExecutorService executor) {
    this.executor = executor;
  }

  @Override
  public void printInternals() {
    System.out.println("Blue Executor: " + executor);
  }
}

RedModule, RedService and RedServiceImplすべてがそれぞれBlue*のクラスを反映しています。

最後に、 and と独自のものMyServiceを使用します。RedBlue ServicesExecutorService

class MyServiceImpl implements MyService {
  private final ExecutorService executor;
  private final RedService red;
  private final BlueService blue;

  @Inject
  MyServiceImpl(final ExecutorService executor, final RedService red, final BlueService blue) {
    this.executor = executor;
    this.red = red;
    this.blue = blue;
  }

  @Override
  public void printInternals() {
    System.out.println("My Executor: " + executor);
    red.printInternals();
    blue.printInternals();
  }
}
4

1 に答える 1