Where to keep eye injections?

What is your advice?

I found the most suitable solution for me - keep injectors and modules in enumeration classes. Benefits:

  • injectors and modules created once
  • nozzles can be used from different classes at application startup (not only at startup),
  • nozzles are stored in one place and can be easily found.

Example:

import static ru.package.Modules.*; public enum Injectors { FOO_INJECTOR(BarModule.module()), FOO2_INJECTOR(FOO_INJECTOR.injector(), Bar2Module.module(), FooModule.module()); private final Injector m_injector; Injectors (Module... modules) { m_injector = Guice.createInjector(modules); } Injectors (Injector parentInjector, Module... modules) { m_injector = parentInjector.createChildInjector(modules); } public Injector injector() { return m_injector; } } 
+4
source share
2 answers

It looks like you basically don’t understand how dependency injection works. If you try to use the Injector link anywhere in your code except where you download the application, you do not use dependency injection, instead you use it as a service locator. You must prepare Injector when you need to test a class, and your classes do not specify in their constructors what their dependencies are (since who knows what they will choose from Injector in some if they have or can get a link to it). In fact, using enum , as you described here, is even worse: you cannot change the configuration at all, even for testing, because your modules are hard-coded into an enumeration.

With dependency injection, classes only declare their dependencies and allow Injector to work transparently (after the initial call to get the root application object) to provide all of these dependencies. This makes it easier to understand, test, and change the functionality of your code. Anyway, I would suggest learning more about how DI and Guice are meant to be used ... you really shouldn't.

+16
source

The bigger question is why?

It is not necessary to keep the Injector around, because after the injection is complete, the Injector must be completed and must disappear.

If you really need an Injector , you could not simply:

 @Inject private Injector injector; 

Is this application a website or is it standalone?

+5
source

Source: https://habr.com/ru/post/1299935/


All Articles