Niraj Chauhan

Niraj Chauhan

#father #husband #SoftwareCraftsman #foodie #gamer #OnePiece #naruto

Java Vert.x MongoDB Client with Guice

Posted by on

Vert.x is an event-driven non-blocking library. It’s not a framework, so you get power to write code in your way. Vert.x is similar to NodeJS. It helps you to achieve concurrency with minimal hardware.

A few months back when I started with vert.x, I was impressed with the documentation and examples what they have on their website. Because, Vert.x is not a framework sometimes it becomes difficult for a developer to construct the entire architecture. When I started, I was facing trouble in getting the DB client available in different services. I didn’t want to initialize it again and again, so I decided to use DI. I started with Google’s Guice.

Here is my implementation.

AppInjector.java (Guice Injection class)

public class AppInjector extends AbstractModule {
    private Vertx vertx;

    public AppInjector(Vertx vertx) {
        this.vertx = vertx;
    }

    @Override
    protected void configure() {

        JsonObject mongoConfig = Config.getObject("mongo_config");
        MongoClient mongo = MongoClient.createShared(vertx, mongoConfig);
        bind(MongoClient.class).annotatedWith(Names.named("MongoClient")).toInstance(mongo);
    }
}

Above I created mongo client and bounded it with Guice. Now where ever I want to use this mongo client, I simply use named annotations and Guice injects the client.

So now in my service I simply do the injection:

MongoService.java

public class MongoService {
    @Inject
    @Named("MongoClient")
    private MongoClient client;

}

That’s it, isn’t that simple? Vert.X is really powerful. You can scale Vert.x application by creating multiple verticles. Polyglot, Vert.x can be used in Java, Javascript, Groovy, Ruby & Ceylon.

You can find the entire implementation on my Github repo.