custom Guice binding annotations with parameters

前端 未结 4 520
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 03:41

I have successfully created a Guice binding annotation to inject single threaded java.util.concurrent.ExecutorService instances into a constructor.

here is an exampl

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 04:22

    You can do this sort of thing (I once did almost exactly this) with Guice, but Guice really needs to know up-front what it's binding. So you would need to do something like:

    for (int i=1; i < 100; i++) {
      ExecutorService svc = Executors.newFixedThreadPool(i);
      bind (ExecutorService.class).annotatedWith(new MultiThreadedImpl(i)).toInstance(svc);
    }
    

    (or more likely, bind to a Provider that lazily initializes it).

    This is ugly enough that you probably don't actually want to do it. It's more useful to just use @Named and have a handful of ExecutorService instances which are tied to a name for the specific thing they are good for, anyway - then you can configure how many threads are used in one place, rather than having to wonder "is anybody using a 73-thread ExecutorService?"

提交回复
热议问题