5

Generic Type Injection Examples in Bootique and Guice

 3 years ago
source link: https://nixmash.com/java/generic-type-injection-examples-in-bootique-and-guice/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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…

jsoupann0526a.png

the following annotated property…

@Selector("#myid")
@TextValue
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.

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

Then instantiated in a class with its Qualifier.

@Autowired
@Qualifier("jsoupPostParser")
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.

generics0328a.png

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

generics0328b.png

Using Injection in our Application

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

generics0328c.png

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.

generics0328d.png

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK