Home Programming Mastering Spring Boot 2.0

Mastering Spring Boot 2.0

By Dinesh Rajput
books-svg-icon Book
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with Spring Boot 2.0
About this book
Spring is one of the best frameworks on the market for developing web, enterprise, and cloud ready software. Spring Boot simplifies the building of complex software dramatically by reducing the amount of boilerplate code, and by providing production-ready features and a simple deployment model. This book will address the challenges related to power that come with Spring Boot's great configurability and flexibility. You will understand how Spring Boot configuration works under the hood, how to overwrite default configurations, and how to use advanced techniques to prepare Spring Boot applications to work in production. This book will also introduce readers to a relatively new topic in the Spring ecosystem – cloud native patterns, reactive programming, and applications. Get up to speed with microservices with Spring Boot and Spring Cloud. Each chapter aims to solve a specific problem or teach you a useful skillset. By the end of this book, you will be proficient in building and deploying your Spring Boot application.
Publication date:
May 2018
Publisher
Packt
Pages
390
ISBN
9781787127562

 

Chapter 1. Getting Started with Spring Boot 2.0

As we know, the Spring Framework makes development very easy for both core and enterprise Java applications. Spring has settled, and is now a very popular framework. The Spring team is continuously inventing something new to enhance software development and they are focused on making software development easy. The Spring team released one of its major projects for the Spring Framework in 2013, Spring Boot.

This project from the Spring team makes software development with Java easy. Spring Boot is built on top of the existing Spring Framework. So basically, Spring Boot is not a separate framework, but it is similar. It's a collection of ready-made things to just pick and use without taking any overhead configuration.

The Spring team is introducing many exciting things to the Spring ecosystem to sustain it in the market. There are many new things such as cloud computing, big data, schemaless data persistence, and reactive programming. But one of the most exciting and game changing features has come with Spring Boot in the past year. Spring Boot is a great invention for the Spring Framework by the Spring team. That is why Spring has settled for a long time and is winning major laurels.

Spring Boot is a tricky framework to understand. This chapter will help you to understand Spring Boot 2.0 and the underlying important concepts—starter projects, auto-configuration, and starter parents. You will also understand how Spring Boot makes software development easy. As a bonus, I will discuss the story behind the success of Spring Boot. This chapter will cover a demo application with Spring Boot and create a REST service.

At the end of this chapter, you will understand how Spring Boot develops Spring applications with agility and provides an already prepared menu for creating a REST service. You will learn how Spring Boot solves common problems at the configuration level of an enterprise application by using auto-configure.

This chapter will cover the following points:

  • Introducing Spring Boot
  • Simplifying Spring application development using Spring Boot
  • The essential key components of Spring Boot
    • Spring Boot Starter projects
    • Auto-configuration
    • Spring Boot CLI
    • Spring Boot Actuator
  • Setting up a Spring Boot workspace
  • Developing your first Spring Boot application
  • New features in Spring Boot 2.0

Let's look at these topics in detail.

 

Introducing Spring Boot


In my opinion, Spring Boot is like a cooked meal waiting to be eaten. In terms of Spring application development, Spring applications typically require a lot of setup. Suppose you are working with JPA. You need DataSource, TransactionManager, EntityManagerFactory, and so on. If you are working with a web MVC application, you need WebApplicationInitializer/web.xml, ContextLoaderListener, and DispatcherServlet. If you are working on an MVC application using JPA, you would need all of these. But much of this is predictable. Spring Boot can do most of this setup for you.

Spring Boot provides a new strategy for application development with the Spring Framework, with minimal fuss. It enables you to focus only on the application's functionality rather than Spring metaconfiguration. Spring Boot requires either minimal or zero configuration in the Spring application.

According to the Spring Boot documentation:

"Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run.""

Spring Boot has changed the way Spring applications are being developed. If you look at the initial versions of the Spring Framework, Spring was a very lightweight and POJO-oriented framework. That means it was decoupled and had less component code, with configurations being set up using XML. As of Spring version 2.5, annotations were introduced, which reduced the XML configurations by using component-scanning. Spring 3.0 came with Java configuration; do note that there was still no escape from configuration. Eventually, with the latest Spring version, component-scanning reduced configuration and Java configuration made it less time-consuming, but Spring still required a lot of configuration.

All these configurations in the Spring application affect the development of actual business functionality. It works as a source of friction in Spring application development. There is no doubt the Spring Framework does much more for us in the area of application development using Java. But if a mistake happened in the configuration level, it required a lot of time to debug and solve it.

Another point of friction is project dependency management. Adding dependencies is very hectic work that gives developers headaches when it comes to deciding what libraries need to be part of the project build. It is even more challenging to identify the versions of depending libraries.

Overall, you can see that configurations, dependency management, and deciding versions of depending libraries consume a lot of the development time of the software engineer. Finally, it reduces the productivity of developers.

Spring Boot has changed all of that, but remember it is not a code generator or an IDE plugin.

Spring Boot has an opinionated view of the Spring application. An opinionated runtime for Spring Projects supports different project types, such as Web and Batch, and it handles most low-level, predictable setup for you.

What is an opinionated runtime? Spring Boot uses sensible defaults, opinions, mostly based on the classpath contents. For example, it sets up a JPA Entity Manager Factory if a JPA implementation is on the classpath. Spring Boot uses a default Spring MVC setup if Spring MVC is on the classpath. Still, everything can be overridden easily, but most of the time there is no need to override anything.

Let's see how Spring Boot simplifies Spring application development.

 

Simplifying Spring application development using Spring Boot


As we have discussed in the previous section, the Spring Framework provides lot of flexibility to configure beans in the Spring application in multiple ways such as XML, annotation, and Java configuration. But remember, if the number of modules and features increases in the Spring application, it also increases the complexity in the configuration. After a point, your Spring application tends to become tedious and error-prone.

Here, Spring Boot comes into the picture to address the complexity of the configuration of your Spring application.

Spring Boot does exactly what you are looking for. It will do things automatically for you but allows you to override the defaults if required. (Remember the point about it being an opinionated framework?)

Spring Boot is not a separate framework, but it is Spring at heart. It is built on top of the Spring Framework to remove tedious work from the developer end and allow developers to focus on the business code with minimal or zero configurations.

See the following diagram that shows what Spring Boot is exactly:

In the preceding diagram, you can see that Spring Boot is the surface layer over the Spring Framework, with all of the modules such as Web (MVC), JDBC, Security, Batch, and so on. It presents a small surface area for User to approach and extract value from the rest of Spring.

Suppose you are working with a task, a Hello World web application. If you are choosing to develop with the Spring Framework, what would you need to do?

The following are the bare minimum configurations required for a small web application:

  • Creating a project structure either by using Maven or Gradle and defining required dependencies such as Spring MVC and the Servlet API dependencies for your case.
  • A deployment descriptor file, that is, web.xml. In the case of Java configuration, you require the WebApplicationInitializer implementation class that declares Spring's DispatcherServlet.
  • The Spring MVC configuration class to enable the Spring MVC module for your Hello World application.
  • You have to create a controller class that will respond to your request.
  • You require a web application server such as Tomcat.

Of these points, most are generic boilerplate code and common configuration for a Spring web application, except writing application-specific controllers. So, Spring Boot provides all common configurations and boilerplate code based on the available library of the classpath. You don't need to take responsibility for writing this common and generic code.

Let's create the same Hello World application using Spring Boot. Suppose for a moment we are using a Groovy-based controller class as follows:

@RestController
class HelloController {
   @GetMapping("/")
   String hello() {
         "Hello World!!!"
   }
} 

This code is a complete Spring web application, with nothing required to configure. No web.xml file, no build specification, and not even an application server. This is the entire application. We can run this application using Spring Boot CLI with the following command:

$ Spring run HelloController.groovy

So, you can see how Spring Boot simplifies Spring application development. We will also see the same application using Java in the next section of this chapter.

Note

Spring Boot does not compete with the Spring or Spring MVC Framework. It makes it easy to use them in the Spring application.

 

The essential key components of Spring Boot


You have seen how Spring Boot simplifies Spring application development. But how does Spring Boot make it possible? What is the magic behind it? Spring Boot brings this magic to Spring application development. The following are essential key components of Spring Boot:

  • Spring Boot Starters
  • Automatic configuration
  • Spring Boot CLI 
  • Spring Boot Actuator

These four core key components are the reason behind Spring Boot's magic. These components make Spring application development easy. Let's see these components in detail.

Spring Boot Starters

Starter is like a small Spring project for each module such as web MVC, JDBC, ORM, and so on. For your Spring application, you just add the starters of the respective module in the classpath, and Spring Boot will ensure that the necessary libraries are added to the build by using Maven or Gradle. As a developer, you don't need to worry about the module libraries and dependent versions of libraries, that is, transitive dependencies.

Note

Spring Boot documentation says Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technologies that you need, without having to hunt through sample code and copy-paste loads of dependency descriptors.

Suppose you want to create a web application or an application to expose RESTful services using the Spring web MVC module to your Spring application; just include the spring-boot-starter-web dependency in your project, and you are good to go.

Let's see what it would look like in the Spring application:

<dependencies>
   <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
</dependencies> 

This starter dependency resolves the following transitive dependencies:

  • spring-web-*.jar
  • spring-webmvc-*.jar
  • tomcat-*.jar
  • jackson-databind-*.jar

See the following diagram about spring-boot-starter-web:

The spring-boot-starter not only reduces the build dependency count, but also adds specific functionality to your build. In your case, you added the web starter to your Spring application, so it provides web functionality that your application needs. Similarly, if your application will use ORM, then you can add the orm starter. If it needs security, you can add the security starter.

Spring Boot provides a wide range of Starter projects. Spring Boot provides the following application Starters under the org.springframework.boot group:

  • spring-boot-starter-web-services: For building applications exposing SOAP web services
  • spring-boot-starter-web: Build web applications and RESTful applications
  • spring-boot-starter-test: Write great unit and integration tests
  • spring-boot-starter-jdbc: Traditional JDBC applications
  • spring-boot-starter-hateoas: Make your services more RESTful by adding HATEOAS features
  • spring-boot-starter-security: Authentication and authorization using Spring Security
  • spring-boot-starter-data-jpa: Spring Data JPA with Hibernate
  • spring-boot-starter-cache: Enabling the Spring Framework's caching support
  • spring-boot-starter-data-rest: Expose simple REST services using Spring Data REST

Spring Boot Starter Parent POM

The Starter Parent POM defines key versions of dependencies and Maven plugins. It typically uses spring-boot-starter-parent as the parent in the pom.xml file:

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.0.2.RELEASE</version>
   <relativePath/> <!-- lookup parent from repository -->
</parent> 

Spring Boot Starter Parent POM allows us to manage the following things for multiple child projects and modules:

  • Configuration: Java version and other properties
  • Dependency management: Version of dependencies
  • Default plugin configuration: This includes configurations such as build plugins

It is an easy way to bring in multiple coordinated dependencies including transitive dependencies.

Let's see the Spring Boot auto-configuration.

Spring Boot auto-configuration

Spring Boot can automatically provide configuration for application functionality, which is common to many Spring applications. Auto-configuration works by analyzing the classpath as follows:

  • If you forget a dependency, Spring Boot can't configure it
  • A dependency management tool is recommended
  • Spring Boot Parent and Starters make it much easier
  • Spring Boot works with Maven, Gradle, and Ant/Ivy

Spring Boot offers auto-configuration of those modules in your Spring application based on the JAR dependencies that you have added. Suppose you added the JPA starter dependency (spring-boot-starter-data-jpa) in your Spring application classpath; Spring Boot attempts to automatically configure JPA to your Spring application. Now, you have not manually configured any database connection beans related to JPA. Similarly, if you want to add an in-memory database such as HSQLDB, just add it (org.hsqldb) in the classpath of your Spring application, and it will auto-configure an in-memory database.

Spring Boot provides the auto-configuration feature in the following ways:

  • First, Spring Boot looks for frameworks available on the classpath
  • After that, it checks existing configuration for the application

Based on these points, Spring Boot provides the basic configuration needed to configure the application with these frameworks. This is called auto-configuration.

In another book, Spring 5 Design Patterns, I have written an application related to the backend that accesses a relational database by using JDBC. As we know that the Spring Framework provides JdbcTemplate, we have to register this JdbcTemplate as a bean in the application context of our application as follows:

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
   return new JdbcTemplate(dataSource);
}

This configuration creates an instance of JdbcTemplate and injects it with another bean dependency, DataSource. So, also we have to register this DataSource bean to be met. Let's see in the following configuration how the HSQL database is configured with a DataSource bean:

@Bean
public DataSource dataSource() {
   return new EmbeddedDatabaseBuilder()
         .setType(EmbeddedDatabaseType.HSQL)
         .addScripts('schema.sql', 'data.sql')
         .build();
} 

This configuration creates an instance of DataSource specifying the SQL scripts schema.sql and data.sql with the HSQL embedded database.

You can see that the two bean methods are not too complex to define, but are also not part of the application logic. This represents just a fraction of application configuration. If you add the Spring MVC module to the same application, then you have to register another corresponding bean method. These methods will be the same for each Spring application where you want to use the same modules. We can say that this is boilerplate configuration code in each Spring application.

In short, the configuration, whatever we have defined, is a common configuration for each application. Ideally, we should not have to write it for each application.

Spring Boot addresses this problem of common configuration. It can automatically configure these common configuration bean methods. Spring Boot provides this auto-configuration based on the available library in your application's classpath. So, if we have to add the HSQL database library in your application's classpath, then it will automatically configure an embedded HSQL database.

If a Spring JDBC-related library is in the classpath of your Spring application, then it will also configure a JdbcTemplate bean for your application. There is no need to configure these beans manually in your Spring application. These beans will be automatically configured for you; just use them for business logic. Spring Boot reduces such boilerplate code configuration at the developer's end.

Enabling Spring Boot auto-configuration

Spring Boot provides the @EnableAutoConfiguration annotation that is responsible for enabling the auto-configuration feature. This annotation is used in the main application file of the Spring Boot application. The @EnableAutoConfiguration annotation on a Spring Java configuration class causes Spring Boot to automatically create beans it thinks you need, usually based on classpath contents, that it can easily override.

Let's see the following code that represents the main application launcher class in the Spring Boot application:

@Configuration
@EnableAutoConfiguration
public class MyAppConfig {
   public static void main(String[] args) {
   SpringApplication.run(MyAppConfig.class, args);
   }
} 

But, Spring Boot also provides a shortcut for this configuration file by using another annotation, @SpringBootApplication.

It is very common to use @EnableAutoConfiguration, @Configuration, and @ComponentScan together. Let's see the following updated code:

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

In this code, @ComponentScan, with no arguments, scans the current package and its sub-packages.

Note

@SpringBootApplication has been available since Spring Boot 1.2.

Let's see the following diagram to explain it better than the code:

In this diagram, we can say that the @SpringBootApplication annotation has composed functionality from three annotations—@EnableAutoConfiguration, @ComponentScan, and @Configuration.

Note

Spring Boot Starter reduces a build's dependencies and Spring Boot auto-configuration reduces the Spring configuration.

If you want to exclude auto-configuration for some of the modules, then you use the exclude property of @SpringBootAnnotation. Let's look at the following code:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MyAppConfig {
   ...
} 

As you can see in the code, this Spring Boot application will consider DataSourceAutoConfiguration.class and HibernateJpaAutoConfiguration.class for the auto-configuration.

Let's see the following diagram that explains all about the Spring Boot auto-configuration feature:

As you can see in the diagram, you just include the required modules in your Spring application. At runtime, Spring Boot checks libraries at the classpath of your application. If the required libraries are available on the classpath of your application, then Spring Boot configures the required beans and other configuration for your application. You don't need to worry about the configuration of the modules in the Spring Boot application.

Let's discuss another key component, Spring Boot CLI, in the next section.

Spring Boot CLI

Spring Boot also provides a command-line tool that can be used to quickly write Spring applications. You can run Groovy scripts with Spring Boot CLI. Groovy code has almost zero boilerplate code compared with Java.

The Spring Boot documentation says:

"You don't need to use the CLI to work with Spring Boot but it's definitely the quickest way to get a Spring application off the ground."

Spring Boot's CLI gives you more free time from having to add starter dependencies and auto-configuration to let you focus only on writing your application-specific code. We have seen this in this chapter in the Groovy script HelloController. We can run this Groovy script with Spring Boot CLI.

Spring Boot CLI is a smart tool, because in the Groovy script, if you noticed, there are no import lines. But, Spring Boot CLI allows us to run it. What about dependent libraries, you ask? We don't have Maven or Gradle here. CLI is smart; it detects classes being used in your application and it also knows which Starter dependencies should be used for these classes; accordingly, Spring Boot CLI adds dependencies to the classpath to make it work.

As Spring Boot CLI adds dependencies, a series of auto-configuration kicks in and adds the required bean method configuration so that your application is able to respond to HTTP requests.

CLI is an optional feature of Spring Boot; it just allows you to write a complete application with your application code only as, it doesn't need to build a traditional project. CLI provides tremendous power and simplicity for Spring development. In Chapter 2, Customizing Auto-Configuration in Spring Boot Application, we will see how to set up Spring Boot CLI.

Let's move to another key component of Spring Boot's building blocks. This is Spring Boot Actuator, which gives us insight about running a Spring Boot application.

Spring Boot Actuator

There are a lot of frameworks that provide tools for application development. But Spring Boot doesn't only provide application development-specific features; it also provides a post-production grade feature. This allows you to monitor your Spring application during production using HTTP endpoints or with JMX.

Spring Boot Actuator is the final key component of its building blocks. Other parts of Spring Boot's building blocks simplify Spring development; the Actuator instead offers the ability to inspect the internals of your application at runtime. The Actuator provides data on auditing, metrics, and the health of your Spring Boot application using HTTP endpoints or with JMX. It helps to you manage your application when it's pushed to production.

The Actuator installed in a Spring Boot application provides the following benefits:

  • It provides details of all beans configured in the Spring application context
  • Actuator also provides details about Spring Boot's auto-configuration
  • It also ensures all environment variables, system properties, configuration properties, and command-line arguments are available to your application
  • The Actuator gives various metrics pertaining to memory usage, garbage collection, web requests, and data source usage
  • It provides a trace of recent HTTP requests handled by your application
  • It also gives information about the current state of the threads in the Spring Boot application

Spring Boot Actuator provides the listed information in two ways:

  • You could use web endpoints
  • Or you could use it via a shell interface

We'll explore Spring Boot Actuator's capabilities in detail when we get to Chapter 3, Getting Started with Spring CLI and Actuator.

We have seen all the building blocks of Spring Boot. These blocks serve to simplify Spring application development in its own way.

Now, let's move to the next section of this chapter, and see how to set up a Spring Boot workspace to develop your first Spring Boot application.

 

Setting up a Spring Boot workspace


Let's see how to set up a Spring Boot workspace to create a Spring Boot application. No special tool integration is required to set up a Spring Boot application. You can use any IDE or text editor. But, Spring Boot 2.0's minimum system requirements are as follows:

  • Java SDK v1.8 or higher
  • Spring Framework 5.0.0.RELEASE or above
  • Maven (3.2+) and Gradle 4
  • Tomcat 8.5, that is, a Servlet 3.0+ compatible container

Let's see the following ways to set up the workspace for the Spring Boot application:

  • Set up Spring Boot with Maven
  • Set up Spring Boot with Gradle

Now, we will explore how to set up a Spring Boot application with Maven and Gradle in detail.

Setting up Spring Boot with Maven

Spring Boot is compatible with Apache Maven 3.2 or above. If your machine doesn't already have Java 8 or above, first download Java 8 or above from Oracle's official website:

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

And if you don't already have Maven, first download it from https://maven.apache.org/; Ubuntu users can run sudo apt-get install maven. Let's see the following Spring Boot dependencies with the org.springframework.boot groupId:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.0.2.RELEASE</version>        <relativePath/> <!-- lookup parent from repository -->   </parent>

   <dependencies>
        <dependency>               <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

   </dependencies>
   ...
   ...
</project> 

This .pom file is the minimum requirement for the Spring Boot 2.0 application.

Let's see the Gradle setup for the Spring Boot application.

Setting up Spring Boot with Gradle

We have seen that Java 8 is the minimum requirement for Spring Boot 2.0, both with Maven and Gradle. However, if you want to use Gradle, then first install Gradle 4 or above in your machine from www.gradle.org/.

Now, see the following Gradle Spring Boot dependencies file with org.springframework.boot groupId. Here's what the build.gradle file should look like:

buildscript {
   repositories {
         jcenter()
         maven { url 'http://repo.spring.io/snapshot' }
         maven { url 'http://repo.spring.io/milestone' }
   }
   dependencies {
         classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.0.0.M7'
   }
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

jar {
   baseName = 'HelloWorld'
   version =  '0.0.1-SNAPSHOT'
}

repositories {
   jcenter()
   maven { url "http://repo.spring.io/snapshot" }
   maven { url "http://repo.spring.io/milestone" }
}

dependencies {
   compile("org.springframework.boot:spring-boot-starter-web")
   testCompile("org.springframework.boot:spring-boot-starter-test")
}
 

The preceding Gradle file has minimum requirements for the Spring Boot application. You could use either Maven or Gradle since the process is the same. Spring Boot creates an application using the same process.

Let's create your first Spring Boot application and see how to set up the project's structure using Spring Boot Initializr.

 

Developing your first Spring Boot application


Let's create a Hello World REST application in Java, and create a simple REST service that returns the Hello World message on request. In this application, we will use Maven to build this project.

You would have noticed that whenever you create a simple project structure, you face some difficulties to create it. Where will you place configuration files, properties files, and so on, and build files with dependencies? Traditionally, to resolve this problem and find an easy solution for the project structure, you would have to go to Google and search multiple blogs. I have spent quite some time doing this!

However, things have changed because the Spring Boot team has provided a solution for the project structure. This is the Spring Boot Initializr.

The Spring Boot Initializr provides solutions to all these problems related to setup work, and it creates a more traditional Java project structure.

The Spring Boot Initializr is nothing but a web application that can create a Spring Boot project structure for you. It generates a basic project structure, either a Maven or Gradle build specification; it depends on you what you choose from the menu. But remember, it doesn't generate any application code. You can use this Spring Initializr in several ways:

  • Spring Boot Initializr through a web-based interface (https://start.spring.io)
  • You can also use it through an IDE such as Spring Tool Suite (STS) and IntelliJ IDEA
  • Using the Spring Boot CLI

We will explore Spring Initializr with Spring Boot CLI in Chapter 3, Getting Started with Spring CLI and Actuator. Let's check the other two ways of using Spring Initializr and start with the web-based interface.

Using a web interface for Spring Initializr

The Spring team provides a web application hosted at: https://start.spring.io. It is the most simple way to create a Spring Boot application and the most straightforward way to use the Spring Initializr. It has all the menu options for you, just choose them and use them in your application.

Let's see the following screenshot of what the home page look like:

As you can see, there are a number of options you need to fill in. They are:

  • Project type: Maven or Gradle
  • Language: Java, Kotlin, or Groovy
  • Spring Boot version

On the SPRING INITIALZR home page, on the left side of the form, it asks to specify minimum project metadata, so you must provide the project's Group and Artifact.

You can enter minimal details for whatever SPRING INITIALZR asks about your application, pick your build system, favorite language, and version of Spring Boot you wish to use, whatever you want. After that, choose your application's dependencies from the menu and also provide your project's Group and Artifact. Click the Generate Project button, and we have a ready-to-run application.

Here, I have selected the Spring Boot 2.0.2, Maven build from the drop-down menu and Java as the language from the drop-down menu. Next, I have given my project's Group and Artifact as follows:

  • Groupcom.dineshonjava.masteringspringboot
  • Artifactmastering-spring-boot

Let's see another interesting thing about the web-based interface. Once you click the Switch to the full version link at the bottom of the web interface, it expands to provide more options. It lets you pick the ingredients for your application, like picking off a delicious menu. And also, you can specify additional metadata such as version and base package name.

As you can see in the previous screenshot, I have added some more ingredients such as project description, package name, packaging style (either JAR or WAR), and you could also choose a Java version as well. Let's click on the Generate Project button on the form to have Spring Initializr generate a project for you.

Spring Initializr presents this project to you as a ZIP file, named as the value in the Artifact field, that is downloaded by your browser. In our case, this ZIP file is named mastering-spring-boot.zip.

Let's unzip this file and you will have a project structure as follows:

As you can see, there's very little code in this project and it also creates a couple of empty directories. The generated project contains the following:

  • pom.xml: A Maven build specification
  • MasteringSpringBootApplication.java: A class with a main() method to bootstrap the application
  • MasteringSpringBootApplicationTests.java: An empty JUnit test class instrumented to load a Spring application context using Spring Boot auto-configuration
  • application.properties: An empty properties file for you to add configuration properties to as you see fit
  • static directory: Here, you can put any static content (JavaScript, style sheets, images, and so on) to be served from the web application
  • templates directory: Here, you can put templates that render model data

Finally, import this project to your favorite IDE. If you are using the Spring Tool Suite IDE, it supports creating Spring Boot applications, so you don't need to go to the web-based interface.

Let's have a look at how to create a Spring Boot project by using the STS IDE.

Creating a Spring Boot project using the STS IDE

Spring Tool Suite is one of most popular IDEs for Java developers to develop Spring-based applications. If you don't have STS in your machine, first download the latest version of STS from the following link:

http://spring.io/tools/sts

Let's create a new Spring Boot application in the STS by selecting the New | Spring Starter Project menu item from the File menu. Let's see the following screenshot; STS will present you with a dialog box:

As you can see in the screenshot, this dialog box asks for the same information as the web-based Spring Initializr. So, let's fill it in with the same information, whatever we filled in the web-based Spring Initializr with.

Let's click the Next button. It will present us with a second dialog box like the one shown in the following screenshot:

Let's click on the Finish button. It will present the project structure in your workspace with the same directory structure and default file as the web-based approach presented to you in the ZIP file.

You must be connected to the internet in order for it to work, because STS internally delegates to the Spring Initializr at http://start.spring.io to produce the project.

Now that the project has been imported into your workspace, let's create your application files, such as controllers.

 

Implementing the REST service


Let's start by creating a simple REST controller as follows:

package com.dineshonjava.masteringspringboot.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

   @GetMapping("/hello")
   String sayHello(){
         return "Hello World!!!";
   }
} 

Let's see this small REST controller (HelloController) in detail:

  • @RestController annotation: It indicates that this is the controller class and its result writes into the response body and doesn't want to render view
  • @GetMapping annotation: It indicates a request handler method and it is a shorthand annotation for @RequestMapping(method = RequestMethod.GET)
  • sayHello() method: It returns a greeting message

In the STS IDE, you could run your application as a Spring Boot application with an embedded server by selecting Run As | Spring Boot Application from the Run menu as follows:

Spring Initialzr creates the main application launcher class as follows:

package com.dineshonjava.masteringspringboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MasteringSpringBootApplication {

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

This tiny class is actually a fully operational web application! Let's see some details:

  • @SpringBootApplication: This annotation tells Spring Boot, when launched, to scan recursively for Spring components inside this package and register them. It also tells Spring Boot to enable auto-configuration, a process where beans are automatically created based on classpath settings, property settings, and other factors.
  • main() method: It is a simple public static void main() method to run the application.
  • SpringApplication.run(): The SpringApplication class is responsible for creating the Spring application's context, and the run() method initializes the application's context in your Spring application.

Let's run your Spring Boot application and observe the logs on the console as follows:

As you can see in the console logs, you can observe several things:

  • Logs have the Spring Boot banner at the top of the logs and Spring Boot version. You can also add your own ASCII banner by creating banner.txt or banner.png and putting it into the src/main/resources/ folder.
  • There is an embedded Tomcat server with the server port 8080; it is the default port, but you can customize it by adding the server.port property to the application.properties file as follows:

server.port= 8181

  • Logs also shows all possible request mappings of your application as follows:

As you can see, your application is running on the default embedded Tomcat server with the default server port, 8080. Let's verify it on the system browser, where it will look as follows:

In this chapter, we have created a very simple Hello World REST application and run this application on the embedded Tomcat server of Spring Boot.

Let's see what new features and enhancements have been added to the new version of Spring Boot, 2.0.

 

New features in Spring Boot 2.0


Spring Boot was first released four years ago in 2014. In 2018, a newer version of Spring Boot was released. There are many new features and updates in Spring Boot 2.0. Here are some of the most important changes:

  • There are many new packages and Starters that help with dependency management.
  • Spring Boot 2.0 also supports auto-configuration. This helps in reducing the configuration that was needed in previous Spring apps.
  • It has introduced better longing through features like Actuator.
  • Software quality testing and utilities have been enhanced. This helps in a better user experience. With spring-boot-devtools, you can have much more enhanced feedback loops.
  • Spring Boot 2.0 supports Java version 8 and greater only. It is one of the few options available where you can use the latest Java 9.
  • The Gradle plugin is replaced by BootJar and BootWar.
  • The dependency management plugin is no longer activated automatically.
  • It's far more secure.
  • Reactive models have new starters of different types, such as WebFlux.
  • Actuator has been upgraded with huge changes. Earlier, only Spring MVC could be supported by Actuator, but with version 2.0, Actuator is independent.

You can see that a lot of exciting new features and enhancements can be found in Spring Boot 2.0. So in this book, we will look at many of these new features with examples.

 

Summary


This chapter has given you a quick overview of what Spring Boot has to offer. In this chapter, we have learned how Spring Boot simplified Spring application development. Spring Boot made this magic possible by using its key components such as Spring Boot auto-configuration, Starters, Spring Boot CLI, and Spring Boot Actuator. You can take advantage of Spring Boot Starter dependencies and auto-configuration; you can do rapid development of the Spring application by just focusing only on the application logic, rather than configurations and build dependencies, libraries, and version management. Meanwhile, auto-configuration frees you from boilerplate configuration.

We have also created a very simple Hello World REST application by using the web-based Spring Initializr and Spring Tool Suite IDE, and we have run this application, where we used the embedded Tomcat container.

In Chapter 2, Customizing Auto-Configuration in Spring Boot Application, we'll dive deeper into Spring Boot auto-configuration and its customization in the Spring Boot application.

 

About the Author
  • Dinesh Rajput

    Dinesh Rajput is a founder of Dineshonjava (dot) com, a blog for Spring and Java techies. He is a Spring enthusiast and a Pivotal Certified Spring Professional. He has written two bestselling books, Spring 5 Design Patterns and Mastering Spring Boot 2.0. Mastering Spring Boot 2.0 is the Amazon #1 best-selling book on Java. He has more than 10 years of experience with various aspects of Spring and cloud-native development, such as REST APIs and microservice architecture. He is currently working as an architect at a leading company. He has worked as a tech lead at Bennett, Coleman & Co. Ltd, and Paytm. He has a master's degree in computer engineering from JSS Academy of Technical Education, Noida, and lives in Noida with his family.

    Browse publications by this author
Latest Reviews (5 reviews total)
Smooth Purchase, but still website needs major performance improvements.
Excelent user experience, fast payment approval and pdf download. Very easy and practical.
This book is full of well explained, practical examples. Very good content
Mastering Spring Boot 2.0
Unlock this book and the full library FREE for 7 days
Start now