Ensure Module Is Loaded Only Once In Guice

后端 未结 3 782
离开以前
离开以前 2020-12-07 01:13

Having to deal with Guice, I wonder how I should handle dependencies in terms of modules.

In Guice every module is provided by an instance. So if I have a module req

3条回答
  •  庸人自扰
    2020-12-07 01:22

    Since Guice do not support certain needed functionality it must be emulated. The multibinder code provides one idea. Another idea I currently use is using reflection to find the top most binder during the injector build process. Knowing this binder one can easily add required meta information and track certain objects.

    Those meta information will be dropped once the build process finished.

    Usually one only builds one injector at a time but to be sure we should protect against this.

    So take a look at the single most Binder implementation (RecordingBinder). It provides a field parent that we can walk to the root binder element. Usually Guice will use a single most binder but in case of private modules.

    Another idea being not so secure but come without reflection is using a thread local if you can ensure that only one Guice injector is build at a time.

    Being able to identify the build process and track which builders are used at a time one is able to add any kind of additional logic into guice like preventing to install a dependency twice.

提交回复
热议问题