Book Image

Mastering Spring Boot 2.0

By : Dinesh Rajput
Book Image

Mastering Spring Boot 2.0

By: Dinesh Rajput

Overview of 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.
Table of Contents (23 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Index

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.