Converting the sample application to Spring Boot

CWC
9 Min Read

Last time I gave a brief introduction to Spring and Hibernate and assembled a simple project which holds a Book entity in the database.

Well this is good but just for the beginning. Now it is time to take a step further and convert out application to a Spring Boot application which makes it easy to have a web application up and running.

And by web application I mean web application: we will extend the core functionality of the application to have a Restful endpoint which enables the users of the application to qurey the books in the database. And this is only the beginning.

What is Spring Boot?

First of all let’s take a look at the Spring Boot project. As you can see, this project aims to accelerate Spring based development with less configuration and it tries guessing what you want to do and does some “Spring magic” and sets everything up and running without much configuration.

The best thing in Spring Boot web projects is that you can execute them out of a JAR: you do not need a web container (like Tomcat or Jetty) and deploy your WAR file there because Spring Boot packages your application together with a Tomcat instance and you can go for it.

A basic Spring Boot project

The main idea behind Spring Boot projects is that you need to add a specific parent dependency as the base of your project and then add every other dependency you need. If you want to pick up a more complex project, take a look at Spring Initializr{width=80}.

Before I jump right to the migration, let’s set up a basic web project with the help of Spring Boot (you can download the sources to this application too).

The basic minimalistic application consists of a pom.xml file and a main class containing the main method. If you choose to use the basic Spring Boot starter package your application exists after your start it. If you choose a web application as the base your application starts up inside a Tomcat container and it runs — without having any functionality just a basic error page because nothing is found.

In the minimalistic springboot project you find this application — with another dependency: Spring Actuator. This is a basic configuration extension which gives a bit more to your application. If you start the application and open up http://localhost:8080/health you will see a JSON response that the application is up and running.

If you look at the sample application there is almost no code. The application consists only of the Application Java class containing the following code:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

The @SpringBootApplication annotation does all the magic behind this application. It configures some things based on the classpath of your application (based on the dependencies your project relies on).

For extended guide applications visit the Spring IO Guides.

Steps of the migration

After this quick introduction let’s go ahead and convert the example application from the first part of this tutorial to a Spring Boot application.

This migration will consist three main steps:

  1. updating the pom.xml witht the right dependencies
  2. delete most of the code I created last time
  3. add new code to have a RESTful endpoint

I know the first step sounds a bit harsh but it is required because Spring Boot does a lot what I did the last time.

Updating the pom.xml

Deleting code

I am fond of deleting code. That’s because less code is less error prone (well, this is not quite true but let’s pretend this for now). This is why I am happy to delete some of my code to make the application more maintainable.

Let’s start with the Main class. Here I remove all the code and replace it with the contents of the previously mentioned Application class — and I add the @SpringBootApplication too of course.

Because the Main class does not have any Spring configuration related code I feel free to delete the whole ApplicationConfiguration class because this was the main entry point for Spring to look-up the beans of the application. Now Spring Boot does this automatically.

Configuring the RESTful endpoint

Now we have a Spring Boot web application which is up and running but we cannot access the data in the database. This is quite a pity because while preparing the previous article I’ve added some (20) books to the database.

To list these books I will add a RESTful endpoint. For this I will use the already defined ApplicationService class and change the @Service annotation to @RestController. And add the@RequestMapping("/books") to the loadBooks method. This @RequestMapping annotation tells Spring to generate and endpoint and if someone opens up http://localhost:8080/books it will return a list of Book entities in the database — all converted to JSON objects:

However if you joined the article series now I spare you to go through the first part and add through that version new data to the application. Let’s include another basic endpoint to the application.

Beside the loadBooks method there is a saveBook method which takes a Book entity as parameter. Let’s modify this a bit to save the parameter to the database.

@RequestMapping(value = "/books", method = RequestMethod.POST)
public void saveBook(@RequestBody Book book) {
    this.repository.save(book);
}

The code above converts this method to a POST request endpoint — for the same URL as the GET request listens to. The @RequestBody annotation tells Spring to use the provided data (as a JSON object) to convert it to a Book instance and then save it to the database.

To test the application let’s execute the following curl command:

curl -X POST -H "Content-Type:application/json" -d '{"title": "Spring example", "isbn": "unknown"}' http://localhost:8080/books

This adds a new entry to the database with the title Spring example and the ISBN unknown. The ID of the Book is generated automatically by Hibernate.

The Content-Type header is required to tell Spring that we are sending a JSON as parameter so it can convert it to a Book object.

Launching the application

A Spring Boot application can be launched in two ways: from the command line and as a JAR file (which I already mentioned).

The command line version is of course good for development purposes, the JAR is for distributing.

To be honest, the command line version is a Maven command and you can invoke it with mvn spring-boot:run.

To get the JAR version you need two things. First package the application with mvn clean package and then run it with java -jar target/springhibernate-0.0.1-SNAPSHOT.jar.

Both methods are assuming you are in the project’s main folder containing the pom.xml file.

Conclusion

This was a though article with some new concepts and changing the structure of the sample application. However I only scratched the surface and there is much more in Spring Boot, Hibernate and even in REST services to talk about. This is why there are so many books out on the market. You have plenty material to work with.

For example we could introduce entity validation and relations to extend this system: add authors to the books. Or reduce the configuration even more because Spring Boot offers a very minimalistic need of configuration for applications — even with a database behind the scenes.

Download Spring Boot two samples source code

[sociallocker]

[/sociallocker]

Share This Article
1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version