Using HK2 in a basic Jersey Web Service

At work, I do a lot of backend work in C#. I’ve always felt that seeing other frameworks are good to get better. This time, I decided to go with Java, more precisely Jersey.  I’ve come to love dependency injection in .NetCore, therefore using HK2 in a basic Jersey Web Service was first on my play list.

Project bootstrap

I decided to go for a really simple project and bootstrap it using Maven:

This generates a simple server with a single HTTP GET endpoint.

Playing around

I then started adding a few controllers and workflows. Using this setup, each controller needs a handle to a workflow. Of course, this is easier done using dependency injection. I did not want to reuse what I did for my other project, so I explored what Jersey proposes. Quickly I found that Jersey comes with HK2 all ready, so I glimpsed the HK2 introduction and started playing with it.

I added a few @Contract , @Service  and @Inject , and tried it out. Before even waiting for the results, I knew that something was missing. It was either major magic underneath or I was not defining which service I wanted to use for each contract.

And as expected, I got a nice little exception:  org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection [snip]

Fixing it

After a tiny bit of googling and better reading on my part, I figured the issue: you simply need to register a binder into your server configuration. More explicitly, you’ll need the following:

Final part is to use this configuration class when initializing your server, like so:

Sources

  • Jersey, RESTful Web Services in Java
  • HK2, A light-weight and dynamic dependency injection framework
Tagged . Bookmark the permalink.

Leave a Reply