Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Spring Boot Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
Spring Boot Cookbook

Spring Boot Cookbook

By : Alex Antonov
4.6 (5)
close
close
Spring Boot Cookbook

Spring Boot Cookbook

4.6 (5)
By: Alex Antonov

Overview of this book

Spring Boot is Spring's convention-over-configuration solution. This feature makes it easy to create Spring applications and services with absolute minimum fuss. Spring Boot has the great ability to be customized and enhanced, and is specifically designed to simplify development of a new Spring application. This book will provide many detailed insights about the inner workings of Spring Boot, as well as tips and recipes to integrate the third-party frameworks and components needed to build complex enterprise-scale applications. The book starts with an overview of the important and useful Spring Boot starters that are included in the framework, and teaches you to create and add custom Servlet Filters, Interceptors, Converters, Formatters, and PropertyEditors to a Spring Boot web application. Next it will cover configuring custom routing rules and patterns, adding additional static asset paths, and adding and modifying servlet container connectors and other properties such as enabling SSL. Moving on, the book will teach you how to create custom Spring Boot Starters, and explore different techniques to test Spring Boot applications. Next, the book will show you examples of configuring your build to produce Docker images and self-executing binary files for Linux/OSX environments. Finally, the book will teach you how to create custom health indicators, and access monitoring data via HTTP and JMX.
Table of Contents (9 chapters)
close
close
8
Index

Creating a simple application

Now that we have a basic idea of the starters that are available to us, let's go ahead and create our application template at http://start.spring.io.

How to do it…

The application that we are going to create is a book catalog management system. It will keep a record of books that were published, who were the authors, the reviewers, publishing houses, and so forth. We will name our project BookPub, and apply the following steps:

  1. Use the default proposed Group name: org.test.
  2. Enter bookpub for an Artifact field.
  3. Provide BookPub as a Name for the application.
  4. Specify org.test.bookpub as our Package Name.
  5. Choose Gradle Project.
  6. Select Jar as Packaging.
  7. Use Java Version as 1.8.
  8. Use Spring Boot Version as 1.2.5.
  9. Select the H2, JDBC, and JPA starters from the Project Dependencies selection so that we can get the needed artifacts in our build file in order to connect to an H2 database
  10. Click Generate Project to download the project archive.

How it works…

Clicking on the Generate Project button will download the bookpub.zip archive, which we will extract in our working directory. In the newly created bookpub directory, we will see a build.gradle file that defines our build. It already comes preconfigured with the right version of a Spring Boot plugin and libraries and even includes the extra starters, which we have chosen.

The following is the code of the build.gradle file:

dependencies {
  compile("org.springframework.boot:spring-boot-starter-data-jpa")
  compile("org.springframework.boot:spring-boot-starter-jdbc")
  runtime("com.h2database:h2")
  testCompile("org.springframework.boot:spring-boot-starter-test") 
}

We have selected the following starters:

  • org.springframework.boot:spring-boot-starter-data-jpa pulls in the JPA dependency
  • org.springframework.boot:spring-boot-starter-jdbc pulls in the JDBC supporting libraries
  • com.h2database:h2 is a particular type of database implementation, namely H2

As you can see, the runtime("com.h2database:h2") dependency is a runtime one. This is because we don't really need, and probably don't even want, to know the exact kind of a database to which we will connect at the compile time. Spring Boot will autoconfigure the needed settings and create appropriate beans once it detects the presence of the org.h2.Driver class in the classpath when the application is launched. We will look into the inner workings of how and where this happens later in this chapter.

The data-jpa and jdbc are Spring Boot starter artifacts. If we look inside these dependency jars once they are downloaded locally by Gradle, or using Maven Central online file repository, we will find that they don't contain any actual classes, only the various metadata. The two containing files that are of particular interest to us are pom.xml and spring.provides. Let's first look at the spring.provides file in the spring-boot-starter-jdbc.jar artifact, with the following content:

provides: spring-jdbc,spring-tx,tomcat-jdbc

This tells us that by having this starter as our dependency, we will transitively get the spring-jdbc, spring-tx, and tomcat-jdbc dependency libraries in our build. The pom.xml file contains the proper dependency declarations that will be used by Gradle or Maven to resolve the needed dependencies during the build time. This also applies to our second starter: spring-boot-starter-data-jpa. This starter will transitively provide us with the spring-orm, hibernate-entity-manager, and spring-data-jpa libraries.

At this point, we have enough libraries/classes in our application classpath so as to give Spring Boot an idea of what kind of application we are trying to run and what are the kind of facilities and frameworks that need to be configured automatically by Spring Boot in order to stitch things together.


Earlier, we mentioned that the presence of the org.h2.Driver class in the classpath will trigger Spring Boot to automatically configure the H2 database connection for our application. To see exactly how this will happen, let's start by looking at our newly created application template, specifically at BookPubApplication.java located in the src/main/java/org/test/bookpub directory in the root of the project, as follows:

package org.test.bookpub;

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

@SpringBootApplication
public class BookPubApplication {

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

This is effectively our entire and fully runnable application. There's not a whole lot of code here and definitely no mention about configuration or databases anywhere. The key to making magic is the @SpringBootApplication meta-annotation. In order to understand what actually happens, we can take a look inside the code definition for this annotation, where we will find the real annotations that will direct Spring Boot to set things up automatically:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {…}

Let's go through the following list of annotations:

  • @Configuration tells Spring (and not just Spring Boot, as it is a Spring Framework core annotation) that the annotated class contains Spring configuration definitions such as the @Bean, @Component, and @Service declarations, and others.
  • @ComponentScan tells Spring that we want to scan our application packages—starting from the package of our annotated class as a default package root—for the other classes that might be annotated with @Configuration, @Controller, and other applicable annotations, which Spring will automatically include as part of the context configuration.
  • @EnableAutoConfiguration is a part of the Spring Boot annotation, which is a meta-annotation on its own (you will find that Spring libraries rely very heavily on the meta-annotations in order to group and compose configurations together). It imports the EnableAutoConfigurationImportSelector and AutoConfigurationPackages.Registrar classes that effectively instruct Spring to automatically configure the conditional beans depending on the classes available in the classpath. (We will cover the inner workings of autoconfiguration in detail in Chapter 4, Writing Custom Spring Boot Starters).

The SpringApplication.run(BookPubApplication.class, args); line in the main method basically creates a Spring application context that reads the annotations in BookPubApplication.class and instantiates a context, which is similar to how it would have been done if instead of using Spring Boot we would have stuck with the regular Spring Framework.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Spring Boot Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon