Spring Boot 2.0 — Project Structure and Best Practices (Part 1)

Arpit Khandelwal
Mar 31, 2019 · 8 min read

The Spring Framework has been around for over a decade and has found a place as the de facto standard framework for developing Java applications. With such a long and storied history, some might think that Spring has settled, resting on its laurels, and is not doing anything new or exciting. Some might even say that Spring is legacy and that it’s time to look elsewhere for innovation.

Some would be wrong.

There are many exciting new things taking place in the Spring ecosystem, including work in the areas of cloud computing, big data, schema-less data persistence, reactive programming, and client-side application development. Perhaps the most exciting, most head-turning, most game-changing new thing to come to Spring in the past year or so is Spring Boot. Spring Boot offers a new paradigm for developing Spring applications with minimal friction.

— Craig Walls


Preface

I got the inspiration to write this article (first in the series of two) when I was trying to goole my way through the internet to find an ideal project structure (boilerplate) for Spring Boot v2 based projects. Even though Spring Initializr does a decent job to let us create a basic pom.xml (similar to package.json for js developers) using a handy graphical user interface, it doesn’t quite create a complete project structure for us that we can leverage and build our application upon.

Also the fact that there are tons of undocumented github contributions made by spring developers and plethora of misleading articles online, I finally decided to study what’s new in Spring Boot v2 and come up with a project structure that is not just a starting point, but an almost complete bus reservation system of its own written completely in Spring Boot and the user interface designed using Thymeleaf.

In these two articles I would try to cover the basics of the application that I have built along with details on the code structure, various artefacts used for its creation along with some important mini frameworks that I built on the fly to support some of the cross cutting concerns.

Spring Boot

I suppose we all are well aware of the strengths and weaknesses of Spring Framework, specially the complex XML configurations which proved to be a nightmare for enterprise grade applications with hundreds of beans and services to support a requirement.

A lot of work has gone into Spring Boot to reduce complexity and dependencies, which largely alleviates our previous reservations. If you live in a Spring ecosystem and are moving to microservices, Spring Boot is now the obvious choice. Spring Boot allows easy set up of standalone Spring-based applications. It’s ideal for pulling up new microservices and easy to deploy. It also makes data access less of a pain due to the hibernate mappings with much less boilerplate code.

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. It takes an opinionated view of the Spring platform and third-party libraries so that we can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration, it has following distinguishing features:

  • Easy dependency Management
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated ‘starter’ dependencies to simplify your build configuration
  • Automatically configure Spring and 3rd party libraries whenever possible
  • Provide production-ready features such as metrics, health checks and externalised configuration
  • Absolutely no code generation and no requirement for XML configuration
  • DevTools to auto restart server on code/config updates
  • Easy management of profile specific properties

What’s New in Spring Boot v2.0?

Spring Boot 2.0 is the first major revision of Spring Boot since 1.0 was released years ago and it’s also the first GA version of Spring Boot that provides support for Spring Framework 5.0.

  • Minimum version of Java required is Java 8.
  • It supports Java 9 too.
  • Out of the box support for “Reactive Web Programming” with Spring WebFlux.
  • Auto-configuration and starter POMs for reactive Spring Data Cassandra, MongoDB, Couchbase, and Redis.
  • Finally support for HTTP/2.
  • A freshly written Gradle plugin with minimum requirement of Gradle 4.x
  • Support for Kotlin 1.2.x
  • Out of the box support for InfluxDB.

A complete list of changes along with basic upgrade guide is located here.

Bus Reservation System

This starter kit focuses on how to use Spring Boot, following all the best practices that are recommended by Spring Framework 5.0 and Spring Boot v2.0, ensure the code is loosely coupled and that all the layers in the application are completely independent of each other and talk using neutral objects. While writing this kit, I have done sufficient research around the code structure and usage of appropriate design patterns to make this as an excellent starting point to begin coding your own web application.

The kit would have been incomplete if it did not have a concrete use case to implement, here I have taken a case study of a very simple yet worthy Bus Reservation System and tried to implement an Admin portal which can be operated via browser and a series of REST APIs to interact with the system using mobile applications or frontend applications. The complete systems has two prominent actors :

1. Admin user
2. End user

The Admin user can access this application on browser (laptop or mobile/tablet, doesn’t really matter as this is built using bootstrap, material design and is completely responsive) and can perform the following actions :

1. Signup
2. Login (Spring sessions)
3. Update their profile
4. Create an agency
5. Add buses to the agency
6. Add trips consisting of predefined stops and buses

The End user can use their mobile application (yet to be built, however the REST APIs are ready and could be used via Postman or Swagger) to perform the following actions :

1. Signup
2. Login (and get a JWT token)
3. List all available stops
4. Search a trip between any two stops
5. Filter search results with a date option
6. Book a ticket for a given trip schedule

Admin interface and REST APIs both have their independent authentication mechanisms, the web application uses the cookie based authentication (provided by default by Spring security) and the REST API uses the JWT authentication for access. This application assumes the availability of ‘MongoDB’ installation on the localhost where the server will run or the use of docker-compose to boot up a mongodb container and link the application with it within the realm of docker.

Any changes that the admin users will do on the web portal will impact the search results of the end users, there will be certain use cases which you may find missing here, I hope you will appreciate that the overall idea was to present a way to create such an application completely inside the realm of Spring Boot and not to actually building a fully operational reservation system.

The admin user interface is completely written in material design using Bootstrap v4 and is responsive to suite a variety of devices. The template engine used to render the admin views is Thymeleaf since the library is extremely extensible and its natural templating capability ensures templates can be prototyped without a back-end — which makes development very fast when compared with other popular template engines such as JSP.

Database Schema

The current schema looks as follows:

BRS Database Schema (Mongodb)
  • The authentication and authorization is governed by User and Role collection.
  • The Agency collection keeps the details of agency along with who owns it.
  • The Stop collection keeps the data about all the stops in the system.
  • The Bus collection has the data of all the buses for various agencies along with their capacity and make years.
  • The Trip and TripSchedule collections keep the information about all the trips that agency owners create within the system. Information like source and destination stops, journey time, data of travel, tickets sold so far and the available seats is collected in them.
  • Last, the Ticket collection keeps information about all the tickets issued in the application for various trips.

Some of you might wonder the reason behind choosing String data type for the dates instead of Date data type, well, to be honest MongoDB has its own way to deal with dates and tends to use the UTC format which led to some avoidable complications within the codebase and hence the preferred approach was to go with a String instead and do some calculations in house within the java code if needed.

Libraries/Tools Used

Following libraries were used during the development of this starter kit :

  • Spring Boot : Server side framework
  • Docker : Containerising framework
  • MongoDB : NoSQL database
  • Swagger : API documentation
  • Thymeleaf : Templating engine
  • Material : UI themeing/design
  • Bootstrap : CSS framework
  • JWT : Authentication mechanism for REST APIs

User Interface

Here are the various screens of the Admin portal that you should be able to use once the application is setup properly :

Login

Signup

Dashboard

Agency

Buses

Trips

Profile

Part 2

Thanks for reading the first part from a series of two articles on Spring Boot. If this is enough to raise your interest in using this impressive web framework, be sure to check out the second part here.

It contains a detailed walkthrough of the starter-kit app built by me, which provides an excellent starting point for all Spring Boot developers to use in their own production environments. It will cover topics such as the project structure, dockerisation, exception handling, web security, decorated Thymeleaf view layout etc.

If it was interesting or helpful to you, please do press the 👏 clap button and help others find this story too.

Did you know you could give up to 50 claps?

The Resonant Web

Exploring the new era of web development.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade