Guice AssistedInject

Toshiya Komoda
1 min readNov 17, 2019

Dependency Injection

Dependency Injection is a powerful design pattern when you write your systems in object oriented(OO) way. In OO, your system would be divided into a lot of objects which is responsible for small functionality. It allows you to write simple logics and unit tests. However, we have to manage a lot of objects. Those objects might have multiple, nested, and complicated dependency chains. You can do these objects dependency management with plain Java, of course. But, it is getting very painful when the number of objects is getting large. Here, we want more structural way to manage objects dependency. This is where Dependency Injection (DI) and DI library comes.

Guice is one of the most popular DI libraries in Java. A simple example is shown below.

A simplest example of instance creation with Guice

AssistedInject

In more complex case, you may want to write a class whose constructor receives

  1. dynamic instances, which is only known at runtime
  2. static instances, which can be injected by DI library

In this case, we can use FactoryModuleBuilder. FactoryModuleBuilder will auto-generate Factory class which creates the class whose dependencies have both dynamic and static. A simple example code is shown in the example.

This is kind of a mix of Factory and Dependency Injection. It is officially called AssistedInject. You can find more in official Guice document.

--

--