Spring Boot 2 Recipes: A Problem-Solution Approach
()
About this ebook
Using a problem-solution approach, Spring Boot 2 Recipes quickly introduces you to Pivotal's Spring Boot 2 micro-framework, then dives into code snippets on how to apply and integrate Spring Boot 2 with the Spring MVC web framework, Spring Web Sockets, and microservices. You'll also get solutions to common problems with persistence, integrating Spring Boot with batch processing, algorithmic programming via Spring Batch, and much more. Other recipes cover topics such as using and integrating Boot with Spring's enterprise services, Spring Integration, testing, monitoring and more.
What You'll Learn
- Get reusable code recipes and snippets for the Spring Boot 2 micro-framework
- Discover how Spring Boot 2 integrates with other Spring APIs, tools, and frameworks
- Access Spring MVC and the new Spring Web Sockets for simpler web development
- Work with microservices for web services development and integration with your Spring Boot applications
- Add persistence and a data tier seamlessly to make your Spring Boot web application do more
- Integrate enterprise services to create a more complex Java application using Spring Boot
Who This Book Is For
Experienced Java and Spring programmers.
Related to Spring Boot 2 Recipes
Related ebooks
Pro Spring Security: Securing Spring Framework 5 and Boot 2-based Java Applications Rating: 0 out of 5 stars0 ratingsSpring Boot 2: How To Get Started and Build a Microservice - Third Edition Rating: 5 out of 5 stars5/5Spring Start Here: Learn what you need and learn it well Rating: 0 out of 5 stars0 ratingsComputer Programming: From Beginner to Badass—JavaScript, HTML, CSS, & SQL Rating: 3 out of 5 stars3/5Practical Entity Framework: Database Access for Enterprise Applications Rating: 0 out of 5 stars0 ratingsIntroducing Maven: A Build Tool for Today's Java Developers Rating: 0 out of 5 stars0 ratingsBeginning Backbone.js Rating: 3 out of 5 stars3/5Mastering MEAN Stack: Build full stack applications using MongoDB, Express.js, Angular, and Node.js (English Edition) Rating: 0 out of 5 stars0 ratingsMySQL Admin Cookbook LITE: Configuration, Server Monitoring, Managing Users Rating: 4 out of 5 stars4/5MySQL Connector/Python Revealed: SQL and NoSQL Data Storage Using MySQL for Python Programmers Rating: 0 out of 5 stars0 ratingsRSpec Essentials Rating: 3 out of 5 stars3/5Pivotal Certified Professional Core Spring 5 Developer Exam: A Study Guide Using Spring Framework 5 Rating: 0 out of 5 stars0 ratingsSpring Quick Reference Guide: A Pocket Handbook for Spring Framework, Spring Boot, and More Rating: 0 out of 5 stars0 ratingsCode with Java 21: A practical approach for building robust and efficient applications (English Edition) Rating: 0 out of 5 stars0 ratingsFull Stack iOS Development with Swift and Vapor: Full stack iOS development made easy (English Edition) Rating: 0 out of 5 stars0 ratingsBeginning Entity Framework Core 2.0: Database Access from .NET Rating: 0 out of 5 stars0 ratingsSpark: Big Data Cluster Computing in Production Rating: 0 out of 5 stars0 ratingsSpring Boot Cookbook Rating: 0 out of 5 stars0 ratingsBuilding Single Page Applications in .NET Core 3: Jumpstart Coding Using Blazor and C# Rating: 0 out of 5 stars0 ratingsBeginning ASP.NET 4.5 in C# Rating: 0 out of 5 stars0 ratingsReactJS for Jobseekers: The Only Guide You Need to Learn React and Crack Interviews (English Edition) Rating: 0 out of 5 stars0 ratingsGetting Started with Advanced C#: Upgrade Your Programming Skills Rating: 0 out of 5 stars0 ratingsLearning Modular Java Programming Rating: 0 out of 5 stars0 ratingsPractical PHP 7, MySQL 8, and MariaDB Website Databases: A Simplified Approach to Developing Database-Driven Websites Rating: 0 out of 5 stars0 ratings
Programming For You
Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Linux Command Line and Shell Scripting Bible Rating: 3 out of 5 stars3/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5C++ Learn in 24 Hours Rating: 0 out of 5 stars0 ratingsLinux: Learn in 24 Hours Rating: 5 out of 5 stars5/5The Little SAS Book: A Primer, Sixth Edition Rating: 5 out of 5 stars5/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Programming Arduino: Getting Started with Sketches Rating: 4 out of 5 stars4/5Unreal Engine from Zero to Proficiency (Foundations): Unreal Engine from Zero to Proficiency, #1 Rating: 0 out of 5 stars0 ratingsLearn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 0 out of 5 stars0 ratingsWeb Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5Java for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5
Reviews for Spring Boot 2 Recipes
0 ratings0 reviews
Book preview
Spring Boot 2 Recipes - Marten Deinum
© Marten Deinum 2018
Marten DeinumSpring Boot 2 Recipeshttps://doi.org/10.1007/978-1-4842-3963-6_1
1. Spring Boot—Introduction
Marten Deinum¹
(1)
Meppel, Drenthe, The Netherlands
In this chapter you will get a brief introduction to Spring Boot. At the heart of Spring Boot lies the Spring Framework; Spring Boot extends this to make auto-configuration, among others, possible.
Spring Boot makes it easy to create stand-alone, production-grade, Spring-based Applications that you can just run.
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
From the Spring Boot Reference Guide
Spring Boot has auto-configuration for infrastructure like JMS, JDBC, JPA, RabbitMQ, and lots more. Spring Boot also offers auto-configuration for different frameworks like Spring Integration, Spring Batch, Spring Security, and many others. When these frameworks or capabilities are detected, Spring Boot will configure them with opinionated but sensible defaults.
The source code uses Maven for its build. Maven will take care of getting the necessary dependencies, compiling the code, and creating the artifact (generally a jar-file). Furthermore, if a recipe illustrates more than one approach, the source code is classified with various examples with roman letters (e.g., Recipe_2_1_i, Recipe_2_1_ii, Recipe_2_1_iii, etc.).
Tip
To build each application, go inside the Recipe directory (e.g., ch2/recipe_2_1_i/) and execute the mvnw command to compile the source code. Once the source code is compiled, a target subdirectory is created with the application executable. You can then run the application JAR from the command line (e.g., java -jar target/Recipe_2_1_i.jar).
1.1 Create a Spring Boot Application Using Maven
Problem
You want to start developing an application using Spring Boot and Maven.
Solution
Create a Maven build file, the pom.xml, and add the needed dependencies. To launch the application, create a Java class containing a main method to bootstrap the application.
How It Works
Suppose you are going to create a simple application that bootstraps a SpringApplication (the main entry point for a Spring Boot application), gets all the beans from the ApplicationContext, and outputs them to the console.
Create the pom.xml
Before you can start coding you need to create the pom.xml the file used by Maven to determine what needs to be done. The easiest way to use Spring Boot is by using the spring-boot-starter-parent as the parent for your application.
Next you need to add some Spring dependencies to get started using Spring; for this, add the spring-boot-starter as a dependency to your pom.xml.
Notice the fact that there is no version or other information needed; all this is managed because the spring-boot-starter-parent is used as the parent for the application. The spring-boot-starter will pull in all the core dependencies needed to start a very basic Spring Boot application, things like the Spring Framework, Logback for logging, and Spring Boot itself.
The full pom.xml should now look like this.
version=1.0
encoding=UTF-8
?>
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
>
Create the Application Class
Let’s create a DemoApplication class with a main method. The main method calls SpringApplication.run with the DemoApplication.class and arguments from the main method. The run method returns an ApplicationContext, which is used to retrieve the bean names from ApplicationContext. The names are sorted and then printed to the console.
The resulting class would look like the following:
package com.apress.springbootrecipes.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
var ctx = SpringApplication.run(DemoApplication.class, args);
System.out.println(# Beans:
+ ctx.getBeanDefinitionCount());
var names = ctx.getBeanDefinitionNames();
Arrays.sort(names);
Arrays.asList(names).forEach(System.out::println);
}
}
This class is a regular Java class with a main method. You can run this class from your IDE. When the application runs it will show output similar to Figure 1-1.
../images/464036_1_En_1_Chapter/464036_1_En_1_Fig1_HTML.jpgFigure 1-1
Output of running application
What did happen with the code and annotations? The @Configuration annotation makes this class a Spring Java configuration class. Generally when creating an application you also have other components you need to have picked up; for this add the @ComponentScan annotation. Finally, to let Spring Boot do its auto-configuration, add the @EnableAutoConfiguration annotation.
Simplify the Application Class
If you look at the class definition, there are three annotations on it.
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class DemoApplication { ... }
When writing a Spring Boot-based application, most of those require all these annotations. This code can be simplified by using the @SpringBootApplication annotation instead. The class header then becomes
@SpringBootApplication
public class DemoApplication { ... }
The @SpringBootApplication annotation is a so-called composed annotation and consists of the earlier needed annotations.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication { ... }
There is one difference between the @SpringBootApplication and the earlier mentioned annotations. Here the @SpringBootConfiguration annotation is used instead of the @Configuration annotation. The @SpringBootConfiguration is a specialized @Configuration annotation. It indicates that this is a Spring Boot-based application. When using @SpringBootConfiguration in your application, there can only be one class annotated with this annotation!
1.2 Create a Spring Boot Application Using Gradle
Problem
You want to start developing an application using Spring Boot and Gradle.
Solution
Create a Gradle build file, the build.gradle, and add the needed dependencies. To launch the application, create a Java class containing a main method to bootstrap the application.
How It Works
Suppose you are going to create a simple application that bootstraps a SpringApplication, gets all the beans from the ApplicationContext, and outputs them to the console.
Create the build.gradle
First you need to create a build.gradle and use the two plug-ins needed for Gradle to properly manage the dependencies for Spring Boot. Spring Boot requires a special Gradle plug-in (the Spring Boot Gradle plug-in) as well as a plug-in to extend the default dependency management capabilities of Gradle (the dependency management plug-in). To enable and configure these plug-ins, create a buildscript task in your build.gradle.
buildscript {
ext {
springBootVersion = '2.1.0.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath(org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}
)
}
}
This task will now properly configure the Spring Boot plug-in to use. Next you need to specify the plug-ins you want to use; as this is a Java-based project, you at least need the Java plug-in and as this book is about Spring Boot, you will also need the org.springframework.boot plug-in. Finally, you need to include the io.spring.dependency-management plug-in, for letting the Spring Boot Starters manage the dependencies.
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
Finally you will need to add the needed dependencies; just as with Recipe 1.1, add the spring-boot-starter dependency.
dependencies {
compile 'org.springframework.boot:spring-boot-starter'
}
Notice the absence of the specific version on the dependency. Not needing to specify the version, and have it automatically managed, is due to the usage of the io.spring.dependency-management plug-in which, just as with Maven, allows for easier dependency management.
The full build.gradle should now look something like this:
buildscript {
ext {
springBootVersion = '2.1.0.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath(org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}
)
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
dependencies {
compile 'org.springframework.boot:spring-boot-starter'
}
repositories {
mavenCentral()
}
Create the Application Class
Let’s create a DemoApplication class with a main method. The main method calls SpringApplication.run with the DemoApplication.class and arguments from the main method. The run method returns an ApplicationContext, which is used to retrieve the bean names from ApplicationContext. The names are sorted and then printed to the console.
The resulting class would look like the following:
package com.apress.springbootrecipes.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Arrays;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var ctx = SpringApplication.run(DemoApplication.class, args);
System.out.println(# Beans:
+ ctx.getBeanDefinitionCount());
var names = ctx.getBeanDefinitionNames();
Arrays.sort(names);
Arrays.asList(names).forEach(System.out::println);
}
}
This class is a regular Java class with a main method. You can run this class from your IDE. When the application runs, it will show output similar to Figure 1-2.
../images/464036_1_En_1_Chapter/464036_1_En_1_Fig2_HTML.jpgFigure 1-2
Output of running application
1.3 Create a Spring Boot Application Using Spring Initializr
Problem
You want to start a Spring Boot application using Spring Initializr.
Solution
Go to http://start.spring.io , select the Spring Boot version and the different dependencies you think you need, and download the project.
How It Works
First, go to http://start.spring.io , which will open the Spring Initializr (Figure 1-3)
../images/464036_1_En_1_Chapter/464036_1_En_1_Fig3_HTML.pngFigure 1-3
Spring Initializr
Now select what you want to generate (Maven or Gradle). Select the Spring Boot version you want to use; select the most recent one. Next, for the group enter com.apress.springbootrecipes and as artifact leave the default demo value (Figure 1-4).
../images/464036_1_En_1_Chapter/464036_1_En_1_Fig4_HTML.jpgFigure 1-4
Spring Initializr with values
Finally click the Generate Project button; this will trigger a download of a demo.zip. Extract this zip file and import the project into your IDE. After importing, you should have a structure similar to that in Figure 1-5.
../images/464036_1_En_1_Chapter/464036_1_En_1_Fig5_HTML.jpgFigure 1-5
Imported project
Open the pom.xml and compare it with the one from Recipe 1.1 (or build.gradle from Recipe 1.2). It is quite similar; however, there are two differences to note. First there is an additional dependency, spring-boot-starter-test . This pulls in the needed test dependencies like Spring Test, Mockito, Junit 4, and AssertJ. With this single dependency you are ready to start testing.
The second difference is the fact that there is now a build section with the spring-boot-maven-plugin configured.
This plug-in takes care of creating a fat JAR. It takes the original JAR and repackages it with all the dependencies inside it. That way you can just hand over the JAR file to the operations team. The operations team needs to do java -jar
Implement a Simple Application
Open the DemoApplication and update the content to count and obtain the beans from the ApplicationContext.
package com.apress.springbootrecipes.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Arrays;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var ctx = SpringApplication.run(DemoApplication.class, args);
System.out.println(# Beans:
+ ctx.getBeanDefinitionCount());
var names = ctx.getBeanDefinitionNames();
Arrays.sort(names);
Arrays.asList(names).forEach(System.out::println);
}
}
Building the JAR
When using the Spring Initializr, all projects come with the Maven Wrapper (or Gradle Wrapper when using Gradle) to make it easier to build the application. To use the wrapper script, open up a command line. Navigate to the directory the project is in. Finally, execute ./mvnw package or ./gradlew build. This should create the executable artifact in the target (or build/libs) directory.
Now that the JAR has been built, let’s execute it and see what happens. Type java -jar target/demo-0.0.1-SNAPSHOT.jar (or java -jar build/libs/demo-0.0.1-SNAPSHOT.jar) and watch the application start and list the beans from the context (see Figures 1-1 and 1-2).
1.4 Summary
In this chapter you looked at how to bootstrap your development using Spring Boot. We looked at how to get started using Maven as well as Gradle, and finally we looked at how to get started using the Spring Initializer.
In the next chapter we will take a look at basic configuration of a Spring Boot application, how to define a bean, how to use property files, and how to override properties.
© Marten Deinum 2018
Marten DeinumSpring Boot 2 Recipeshttps://doi.org/10.1007/978-1-4842-3963-6_2
2. Spring Boot—Basics
Marten Deinum¹
(1)
Meppel, Drenthe, The Netherlands
In this chapter we will take a look at the basic features of Spring Boot.
Note
To get a starting point, use the Spring Initializr to create a project. No additional dependencies are required, just a Spring Boot project.
2.1 Configure a Bean
Problem
You want Spring Boot to use your class as a bean.
Solution
Depending on your needs, you can either leverage @ComponentScan to automatically detect your class and have an instance created; use it together with @Autowired and @Value to get dependencies or properties injected; or you can use a method annotated with @Bean to have more control over the construction of the bean being created.
How It Works
Recipe 1.1 explained that @SpringBootApplication includes both @ComponentScan and @Configuration. This means that any @Component annotated class will be automatically detected and instantiated by Spring Boot; it also allows for @Bean methods to be defined to declare beans.
Using @Component
First, create a class to bootstrap the application. Create a HelloWorldApplication that is annotated with @SpringBootApplication.
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
Tip
Place the @SpringBootApplication annotated class in a top-level package; this way it will automatically detect all your annotated components, configuration classes, etc. defined in this package and all subpackages.¹
This will bootstrap the application, detect all @Component annotated classes, and detect which libraries are on the classpath (see also Chapter 1). When running this HelloWorldApplication it won’t do much, as there is nothing to detect or to run. Let’s create a simple class that will be automatically detected by Spring Boot.
@Component
public class HelloWorld {
@PostConstruct
public void sayHello() {
System.out.println(Hello World, from Spring Boot 2!
);
}
}
Spring Boot will detect this class and create a bean instance from it. The @PostConstruct annotated method is invoked after construction and injection of all dependencies. Simply put, at startup the sayHello method will run and the console will print the line Hello World, from Spring Boot 2!.
Important
When you need to scan packages not covered by the default component scanning, you need to add a @ComponentScan annotation to your @SpringBootApplication annotated class so that those packages will be scanned as well. These packages are scanned in addition to the default scanning applied through the @SpringBootApplication annotation.
Using @Bean Method
Instead of automatically detecting components, you can also use a factory method to create beans. This is useful if you want or need more control over the construction of your bean. A factory method is a method annotated with @Bean² and it will be used to register a bean in the application context. The name of the bean is the same as the name of the method. The method can have arguments and those will be resolved to other beans in the application context.
Let’s create an application that can do some basic calculations for integers. First let’s write the Calculator; it will get a collection of Operation beans in the constructor. Operation is an interface, and the different implementations will do the actual calculation.
package com.apress.springbootrecipes.calculator;
import java.util.Collection;
public class Calculator {
private final Collection
public Calculator(Collection
this.operations = operations;
}
public void calculate(int lhs, int rhs, char op) {
for (var operation : operations) {
if (operation.handles(op)) {
var result = operation.apply(lhs, rhs);
System.out.printf(%d %s %d = %s%n
, lhs, op, rhs, result);
return;
}
}
throw new IllegalArgumentException(Unknown operation
+ op);
}
}
In the calculate method, the correct Operation is detected using the Operation.handles method ; when the correct one is found, the Operation.apply method is called to do the actual calculation. If we pass in an operation that the calculator cannot handle, an exception is thrown.
The Operation interface is a simple interface with the earlier mentioned two methods.
package com.apress.springbootrecipes.calculator;
public interface Operation {
int apply(int lhs, int rhs);
boolean handles(char op);
}
Now let’s add two operations: one for adding values and one for multiplying values.
package com.apress.springbootrecipes.calculator.operation;
import com.apress.springbootrecipes.calculator.Operation;
import org.springframework.stereotype.Component;
@Component
class Addition implements Operation {
@Override
public int apply(int lhs, int rhs) {
return lhs + rhs;
}
@Override
public boolean handles(char op) {
return '+' == op;
}
}
package com.apress.springbootrecipes.calculator.operation;
import com.apress.springbootrecipes.calculator.Operation;
import org.springframework.stereotype.Component;
@Component
class Multiplication implements Operation {
@Override
public int apply(int lhs, int rhs) {
return