Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Spring Boot 2.0

You're reading from   Mastering Spring Boot 2.0 Build modern, cloud-native, and distributed systems using Spring Boot

Arrow left icon
Product type Paperback
Published in May 2018
Publisher Packt
ISBN-13 9781787127562
Length 390 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Dinesh Rajput Dinesh Rajput
Author Profile Icon Dinesh Rajput
Dinesh Rajput
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Getting Started with Spring Boot 2.0 FREE CHAPTER 2. Customizing Auto-Configuration in Spring Boot Application 3. Getting Started with Spring CLI and Actuator 4. Getting Started with Spring Cloud and Configuration 5. Spring Cloud Netflix and Service Discovery 6. Building Spring Boot RESTful Microservice 7. Creating API Gateway with Netflix Zuul Proxy 8. Simplify HTTP API with Feign Client 9. Building Event-Driven and Asynchronous Reactive Systems 10. Building Resilient Systems Using Hystrix and Turbine 11. Testing Spring Boot Application 12. Containerizing Microservice 13. API Management 14. Deploying in Cloud (AWS) 15. Production Ready Service Monitoring and Best Practices 16. Other Books You May Enjoy

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.

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.

@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.

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.

You have been reading a chapter from
Mastering Spring Boot 2.0
Published in: May 2018
Publisher: Packt
ISBN-13: 9781787127562
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image