Configuring a Generic Type Class as a Spring Bean

We've been talking about the new Jsoup Annotations feature in NixMash Spring which takes a POJO as a Generic Type and returns parsed Jsoup values for the annotated properties. The Jsoup Annotation Parser makes a great example for us on how to wire-up a Class with Generic Types as a Spring Bean.

Let's start by looking at the Jsoup Annotation Parser as our base class.

We have a POJO class named PagePreviewDTO. We'll be passing a Jsoup Document to the JSoupHtmlParser.parse() method and return a populated POJO like this.

PagePreviewDTO pagePreviewDTO = pagePreviewParser.parse(doc);

pagePreviewParser is our Spring Bean, so the question is, how do we create THAT?

We first create a class which extends our JSoupHtmlParser base class, using our POJO as Generic Type parameter.

Now we have something we can work with in Spring! Let's move to our Spring @Configuration class where we configure the PagePreviewParser class we just created as a @Bean. Notice that we do not annotate our extended PagePreviewParser class above (or the base JSoupHtmlParser class) as a Spring @Component.

Now we can create an instance of the bean based on its name pagePreviewParser() and add the Spring @Qualifier annotation which matches its name.

Time to parse and populate with our Spring Bean!

Here's another good reference on this topic from Javabeat if you want to read more.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.

Posted May 26, 2016 02:34 PM EDT

More Like This Post