Dropwizard – Guice – JDBI – Shiro – Liquibase (Part 2)

Use Guice in Dropwizard for dependency injection.

In this second part of the tutorial, I will explain how we used guice in dropwizard to have dependency injection in Ether Mailer.

I assume that you have basic knowledge on Dropwizard and Guice.

While searching a lot and playing around with various modules, I concluded to use the dropwizard-guicey library, created by Vyacheslav Rusakov.

So let’s create a new maven project and add the following dependencies:

<dependency>
    <groupId>ru.vyarus</groupId>
    <artifactId>dropwizard-guicey</artifactId>
    <version>3.1.1</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

The dropwizard-guicey library comes with Dropwizard v. 0.8.5 and Guice v. 4.0

After adding the dependency create a new class, named MyApplication:

The above class bootstraps dropwizard, initializes guice and adds the resource MyResource to serve http requests. We will come to that later.

Create now a new MyGuiceModule class:

public class MyGuiceModule extends DropwizardAwareModule {
 
 @Override
 protected void configure() {
 bind(MySingleton.class).in(Singleton.class);
 }
}

This class is used in order to control guice injections. In the configure method you have the full usage of guice. Furthermore, you may add @Provider guice methods. At the above example, we create a singleton of the class MySingleton.

Now it’s time to create our new resource. Create a new class MyResource:

@Path("/hello")
public class MyResource {

 @Inject
 private MySingleton mySingleton;

 @GET
 public Response helloWorld() {
 return Response.ok("Hello world").build();
 }
}

This class receives GET http requests at path /hello and responds with a hello world. It contains also the singleton instance of the class MySingleton. Try it out!

You may get the guice injector and use it wherever you need it (although bad practice). Just do

Injector injector = guiceBundle.getInjector();

Guice is initialized before Dropwizard (before executing the run method of MyApplication), making it usable in the entire app.

What we learned?

It is pretty simple to add Guice dependency injection and boostrap a brand new Dropwizard application. The most important part is the initialize method of MyApplication.

What’s next?

In the next tutorials I will show you how we used JDBI to query the database.

Thanks for reading the second part of the tutorial. Happy coding!

Write a Reply or Comment

Your email address will not be published. Required fields are marked *

Start sending now. Try our free plan and get 10.000 emails for free!

Create your new account. It's just a few steps!