In this post, we will review how to do dependency injection in Vertx with Google Guice and how to build a basic injection that has the ConfigRetriever component.

In computer science, dependency injection is defined as a pattern, whereby one component gets other components (dependencies) from outside. Numerous posts were written about various implementations of dependency injection in Vertx using the Google Guice library. All of them are good and I do not want to reinvent a bicycle here and repeat the same things again. However, in my opinion, it is a good idea to give a bit more systematic approach to this topic. In my experience, in most cases, for developers is not a big deal to implement a basic DI with Vertx, rather it seems hard to incorporate Vertx components into the DI pipeline. In this post, we will review how to do dependency injection in Vertx with Google Guice and how to build a basic injection that has the ConfigRetriever component (Vertx’s way to obtain an application configuration). Please note, that in this article we use Futures API, so it is focused on Vertx 4.x developers.

Basic DI with Google Guice

Google Guice is an established solution to implement a dependency injection technique in Java applications. Like most established libraries, it is quite simple to use, yet it does not mean that it is limited in any way. This is a very flexible and powerful solution. The main building blocks of the framework are modules and injectors. The module is used to define how to get dependencies. The injector serves as a main entry point of an application and is used for an actual component initialization. Let have a quick example, that uses a constructor injection technique. Imagine, that you develop a verticle, that has two external dependencies — a client class (that performed  HTTP calls) and a repository class (that does database operations). For sure, we will not do here their precise implementations, because it is out of the scope of the post. In order to specify these dependencies classes inside the verticle, we need to use an @Inject annotation. If you are familiar with the Spring framework, you would find a process familiar. Basically, we need to create fields to keep references for components, define a constructor and annotate it with the @Inject, so Guice will know that we use constructor injection.

#java #vert.x #vertx #microservice

Vertx, Guice and Config Retriever: Dependency Injection in Vertx 4.x
2.50 GEEK