Generic Type Injection Examples in Bootique and Guice

Back when I was working in Spring I built a Jsoup Annotation-based parsing library which I blogged about here. It's a pretty cool library that parses file contents into a POJO based on property annotations. For instance, with this HTML…

the following annotated property…

public String myIdText;

would retrieve “This is my id text”.

Injection comes into play because the POJO is passed to the HtmlParser as a Generic Type. In Spring it is defined as a @Bean.

public JsoupHtmlParser<JsoupPostDTO> jsoupPostParser() {
    return new JsoupPostParser(JsoupPostDTO.class);

Then instantiated in a class with its Qualifier.

private JsoupHtmlParser<JsoupPostDTO> jsoupPostParser;

The question then is how do we do the same thing in Bootique, which is based on Guice.

Testing Configuration

We're going to start with configuring the Bootique Test Runtime Environment to use Generic Type injection. We're going to create an instance of the Generic Type as part of the initial @BeforeClass method. This is not how we would normally create an instance in our application, which is why we're looking at the Test Runtime first.

Notice we're binding a Guice TypeLiteral, which is a special class that allows you to specify a full parameterized type. Then we get an Instance of the class using a Guice Key, which consists of an injection type and an optional annotation. Keys support generic types via subclassing just like TypeLiteral.

Now we can use our htmlPageParser in a test like any ordinary class instance.

Using Injection in our Application

Moving from Testing to our Application Runtime Environment we use the Guice TypeLiteral for binding as before.

We're not going to grab an instance in configure() as we did in Testing, but rather create an instance when we need to use our JsoupHtmlParser Generic Type.

Note: If you want the complete Jsoup Annotation-based Parsing source code you will find it in the jsoup Module of my NixMash Spring repository on GitHub.