Generating QR in Spring Boot Application

To generate a QR using Spring Boot we will first start with a fresh spring boot application using spring initializr. For this tutorial, we are going to use Spring Tool Suite (STS), but you are free to use other IDE like InteliJ too.

Visit https://start.spring.io/ and configure as below. We’ll be adding Spring Web dependency for this demonstration as we are going to expose the generation of QR endpoint via a RESTful API. Click Generate. Download the zip file and unzip it.

Now open STS, from the menu bar click File > Open Projects from File System > Import Source > Browse directory and select unzipped project directory (e.g. qr-generation)

In src/main/resources/application.properties let’s configure the server to run at 8080 port by adding below line -

Now, right click on project directory, click Run > Run as Spring Boot App. If everything is configured correctly you’ll be able to see in console that your application is running on port 8080 as configured.

We’ll be using google zxing library to generate QR and to achieve this we need to add below two dependencies in our pom.xml file.

Now, we’ll be creating a Controller to serve as an endpoint for client to request with payload to generate QR with. Right click on src/main/java and create a new package as com.example.qr.controllers. Under this package create a new class and named it as QrGeneratorController. Annotate it with @RestController and @RequestMapping(path = “/api/v1/generate-qr”) to expose/api/v1/generate-qr as an endpoint for client request. And then create a method to process qr generation request and annotate it with @GetMapping annotation.

We also need to define a HttpMessageConverter Bean in the context. To accomplish that, we’re going to create another package as com.qr.example.config and then a new class named BufferedImageConverter under it. Annotate it with @Configuration.

Your API endpoint is ready for qr generation.

http://localhost:8080/api/v1/generate-qr?qrText=Howdy!

Use postman or any web browser to test it.

Full code of this tutorial can be found in below git repository.

Thanks.

Happy Coding!

Software Analyst | AWS Certified Solutions Architect