In this article by, Greg Turnquist, author of the book, Learning Spring Boot – Second Edition, we will cover the following topics:
(For more resources related to this topic, see here.)
Perhaps you've heard about Spring Boot? It's only cultivated the most popular explosion in software development in years. Clocking millions of downloads per month, the community has exploded since it's debut in 2013.
I hope you're ready for some fun, because we are going to take things to the next level as we use Spring Boot to build a social media platform. We'll explore its many valuable features all the way from tools designed to speed up development efforts to production-ready support as well as cloud native features.
Despite some rapid fire demos you might have caught on YouTube, Spring Boot isn't just for quick demos. Built atop the de facto standard toolkit for Java, the Spring Framework, Spring Boot will help us build this social media platform with lightning speed AND stability.
In this article, we'll get a quick kick off with Spring Boot using Java the programming language. Maybe that makes you chuckle? People have been dinging Java for years as being slow, bulky, and not the means for agile shops. Together, we'll see how that is not the case.
At any time, if you're interested in a more visual medium, feel free to checkout my Learning Spring Boot [Video] at https://www.packtpub.com/application-development/learning-spring-boot-video.
What is step #1 when we get underway with a project? We visit Stack Overflow and look for an example project to build a project!
Seriously, the amount of time spent adapting another project's build file, picking dependencies, and filling in other details about our project adds up.
At the Spring Initializr (http://start.spring.io), we can enter minimal details about our app, pick our favorite build system, the version of Spring Boot we wish to use, and then choose our dependencies off a menu. Click the Download button, and we have a free standing, ready-to-run application.
In this article, let's take a quick test drive and build small web app. We can start by picking Gradle from the dropdown. Then, select 1.4.1.BUILD-SNAPSHOT as the version of Spring Boot we wish to use.
Next, we need to pick our application's coordinates:
Now comes the fun part. We get to pick the ingredients for our application like picking off a delicious menu. If we start typing, for example, "Web", into the Dependencies box, we'll see several options appear. To see all the available options, click on the Switch to the full version link toward the bottom.
There are lots of overrides, such as switching from JAR to WAR, or using an older version of Java. You can also pick Kotlin or Groovy as the primary language for your application. For starters, in this day and age, there is no reason to use anything older than Java 8. And JAR files are the way to go. WAR files are only needed when applying Spring Boot to an old container.
To build our social media platform, we need a few ingredients as shown:
The following diagram shows an overview of these ingredients:
With these items selected, click on Generate Project.
There are LOTS of other tools that leverage this site. For example, IntelliJ IDEA lets you create a new project inside the IDE, giving you the same options shown here. It invokes the web site's REST API, and imports your new project. You can also interact with the site via cURL or any other REST-based tool.
Now let's unpack that ZIP file and see what we've got:
We built an empty Spring Boot project. Now what? Before we sink our teeth into writing code, let's take a peek at the build file. It's quite terse, but carries some key bits.
Starting from the top:
buildscript {
ext {
springBootVersion = '1.4.1.BUILD-SNAPSHOT'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
}
}
This contains the basis for our project:
The first piece, the version of Spring Boot, is important. That's because Spring Boot comes with a curated list of 140 third party library versions extending well beyond the Spring portfolio and into some of the most commonly used libraries in the Java ecosystem. By simply changing the version of Spring Boot, we can upgrade all these libraries to newer versions known to work together.
There is an extra project, the Spring IO Platform (https://spring.io/platform), which includes an additional 134 curated versions, bringing the total to 274.
The repositories aren't as critical, but it's important to add milestones and snapshots if fetching a library not released to Maven central or hosted on some vendor's local repository. Thankfully, the Spring Initializr does this for us based on the version of Spring Boot selected on the site.
Finally, we have the spring-boot-gradle-plugin (and there is a corresponding spring-boot-maven-plugin for Maven users). This plugin is responsible for linking Spring Boot's curated list of versions with the libraries we select in the build file. That way, we don't have to specify the version number.
Additionally, this plugin hooks into the build phase and bundle our application into a runnable über JAR, also known as a shaded or fat JAR.
Java doesn't provide a standardized way to load nested JAR files into the classpath. Spring Boot provides the means to bundle up third-party JARs inside an enclosing JAR file and properly load them at runtime. Read more at http://docs.spring.io/spring-boot/docs/1.4.1.BUILD-SNAPSHOT/reference/htmlsingle/#executable-jar.
With an über JAR in hand, we only need put it on a thumb drive, and carry it to another machine, to a hundred virtual machines in the cloud or your data center, or anywhere else, and it simply runs where we can find a JVM.
Peeking a little further down in build.gradle, we can see the plugins that are enabled by default:
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
An up-to-date copy of IntelliJ IDEA can ready a plain old Gradle build file fine without extra plugins.
Which brings us to the final ingredient used to build our application: dependencies.
No application is complete without specifying dependencies. A valuable facet of Spring Boot are its virtual packages. These are published packages that don't contain any code, but instead simply list other dependencies.
The following list shows all the dependencies we selected on the Spring Initializr site:
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-
thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-
websocket')
compile('org.projectlombok:lombok')
runtime('com.h2database:h2')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
If you'll notice, most of these packages are Spring Boot starters:
These starter packages allow us to quickly grab the bits we need to get up and running. Spring Boot starters have gotten so popular that lots of other third party library developers are crafting their own.
In addition to starters, we have three extra libraries:
The value of this last starter, spring-boot-starter-test, cannot be overstated. With a single line, the most powerful test utilities are at our fingertips, allowing us to write unit tests, slice tests, and full blown our-app-inside-embedded-Tomcat tests. It's why this starter is included in all projects without checking a box on the Spring Initializr site.
Now to get things off the ground, we need to shift focus to the tiny bit of code written for us by the Spring Initializr.
The fabulous http://start.spring.io website created a tiny class, LearningSpringBootApplication as shown in the following code:
package com.greglturnquist.learningspringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LearningSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(
LearningSpringBootApplication.class, args);
}
}
This tiny class is actually a fully operational web application!
This little class is runnable. Right now! In fact, let's give it a shot.
. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _
( ( )___ | '_ | '_| | '_ / _` |
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |___, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.1.BUILD-SNAPSHOT)
2016-09-18 19:52:44.214: Starting
LearningSpringBootApplication on ret...
2016-09-18 19:52:44.217: No active profile set, falling
back to defaul...
2016-09-18 19:52:44.513: Refreshing
org.springframework.boot.context.e...
2016-09-18 19:52:45.785: Bean
'org.springframework.transaction.annotat...
2016-09-18 19:52:46.188: Tomcat initialized with port(s):
8080 (http)
2016-09-18 19:52:46.201: Starting service Tomcat
2016-09-18 19:52:46.202: Starting Servlet Engine: Apache
Tomcat/8.5.5
2016-09-18 19:52:46.323: Initializing Spring embedded
WebApplicationCo...
2016-09-18 19:52:46.324: Root WebApplicationContext:
initialization co...
2016-09-18 19:52:46.466: Mapping servlet:
'dispatcherServlet' to [/]
2016-09-18 19:52:46.469: Mapping filter:
'characterEncodingFilter' to:...
2016-09-18 19:52:46.470: Mapping filter:
'hiddenHttpMethodFilter' to: ...
2016-09-18 19:52:46.470: Mapping filter:
'httpPutFormContentFilter' to...
2016-09-18 19:52:46.470: Mapping filter:
'requestContextFilter' to: [/*]
2016-09-18 19:52:46.794: Building JPA container
EntityManagerFactory f...
2016-09-18 19:52:46.809: HHH000204: Processing
PersistenceUnitInfo [
name: default
...]
2016-09-18 19:52:46.882: HHH000412: Hibernate Core
{5.0.9.Final}
2016-09-18 19:52:46.883: HHH000206: hibernate.properties
not found
2016-09-18 19:52:46.884: javassist
2016-09-18 19:52:46.976: HCANN000001: Hibernate Commons
Annotations {5...
2016-09-18 19:52:47.169: Using dialect:
org.hibernate.dialect.H2Dialect
2016-09-18 19:52:47.358: HHH000227: Running hbm2ddl schema
export
2016-09-18 19:52:47.359: HHH000230: Schema export complete
2016-09-18 19:52:47.390: Initialized JPA
EntityManagerFactory for pers...
2016-09-18 19:52:47.628: Looking for @ControllerAdvice:
org.springfram...
2016-09-18 19:52:47.702: Mapped "{[/error]}" onto public
org.springfra...
2016-09-18 19:52:47.703: Mapped
"{[/error],produces=[text/html]}" onto...
2016-09-18 19:52:47.724: Mapped URL path [/webjars/**] onto
handler of...
2016-09-18 19:52:47.724: Mapped URL path [/**] onto handler
of type [c...
2016-09-18 19:52:47.752: Mapped URL path [/**/favicon.ico]
onto handle...
2016-09-18 19:52:47.778: Cannot find template location:
classpath:/tem...
2016-09-18 19:52:48.229: Registering beans for JMX exposure
on startup
2016-09-18 19:52:48.278: Tomcat started on port(s): 8080
(http)
2016-09-18 19:52:48.282: Started
LearningSpringBootApplication in 4.57...
Scrolling through the output, we can see several things:
Spring Boot uses embedded Tomcat, so there's no need to install a container on our target machine. Non-web apps don't even require Apache Tomcat. The JAR itself is the new container that allows us to stop thinking in terms of old fashioned servlet containers. Instead, we can think in terms of apps. All these factors add up to maximum flexibility in application deployment.
How does Spring Boot use embedded Tomcat among other things? As mentioned earlier, it has autoconfiguration meaning it has Spring beans that are created based on different conditions. When Spring Boot sees Apache Tomcat on the classpath, it creates an embedded Tomcat instance along with several beans to support that.
When it spots Spring MVC on the classpath, it creates view resolution engines, handler mappers, and a whole host of other beans needed to support that, letting us focus on coding custom routes.
With H2 on the classpath, it spins up an in-memory, embedded SQL data store.
Spring Data JPA will cause Spring Boot to craft an EntityManager along with everything else needed to start speaking JPA, letting us focus on defining repositories.
At this stage, we have a running web application, albeit an empty one. There are no custom routes and no means to handle data. But we can add some real fast.
Let's draft a simple REST controller:
package com.greglturnquist.learningspringboot;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping
public String greeting(@RequestParam(required = false,
defaultValue = "") String name) {
return name.equals("")
? "Hey!"
: "Hey, " + name + "!";
}
}
Let's examine this tiny REST controller in detail:
If we re-launch the LearningSpringBootApplication in our IDE, we'll see a new entry in the console.
2016-09-18 20:13:08.149: Mapped "{[],methods=[GET]}" onto public
java....
We can then ping our new route in the browser at http://localhost:8080 and http://localhost:8080?name=Greg. Try it out!
That's nice, but since we picked Spring Data JPA, how hard would it be to load some sample data and retrieve it from another route? (Spoiler alert: not hard at all.)
We can start out by defining a simple Chapter entity to capture book details as shown in the following code:
package com.greglturnquist.learningspringboot;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class Chapter {
@Id @GeneratedValue
private Long id;
private String name;
private Chapter() {
// No one but JPA uses this.
}
public Chapter(String name) {
this.name = name;
}
}
This little POJO let's us the details about the chapter of a book as follows:
To interact with this entity and it's corresponding table in H2, we could dig in and start using the autoconfigured EntityManager supplied by Spring Boot. By why do that, when we can declare a repository-based solution?
To do so, we'll create an interface defining the operations we need.
Check out this simple interface:
package com.greglturnquist.learningspringboot;
import org.springframework.data.repository.CrudRepository;
public interface ChapterRepository
extends CrudRepository<Chapter, Long> {
}
This declarative interface creates a Spring Data repository as follows:
Spring Data JPA will automatically wire up a concrete implementation of our interface.
Spring Data doesn't engage in code generation. Code generation has a sordid history of being out of date at some of the worst times. Instead, Spring Data uses proxies and other mechanisms to support all these operations. Never forget - the code you don't write has no bugs.
With Chapter and ChapterRepository defined, we can now pre-load the database, as shown in the following code:
package com.greglturnquist.learningspringboot;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LoadDatabase {
@Bean
CommandLineRunner init(ChapterRepository repository) {
return args -> {
repository.save(
new Chapter("Quick start with Java"));
repository.save(
new Chapter("Reactive Web with Spring Boot"));
repository.save(
new Chapter("...and more!"));
};
}
}
This class will be automatically scanned in by Spring Boot and run in the following way:
With this in place, all that's left is write a REST controller to serve up the data!
package com.greglturnquist.learningspringboot;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ChapterController {
private final ChapterRepository repository;
public ChapterController(ChapterRepository repository) {
this.repository = repository;
}
@GetMapping("/chapters")
public Iterable<Chapter> listing() {
return repository.findAll();
}
}
This controller is able to serve up our data as follows:
If we re-launch our application and visit http://localhost:8080/chapters, we can see our pre-loaded data served up as a nicely formatted JSON document:
It's not very elaborate, but this small collection of classes has helped us quickly define a slice of functionality. And if you'll notice, we spent zero effort configuring JSON converters, route handlers, embedded settings, or any other infrastructure.
Spring Boot is designed to let us focus on functional needs, not low level plumbing.
So in this article we introduced the Spring Boot concept in brief and we rapidly crafted a Spring MVC application using the Spring stack on top of Apache Tomcat with little configuration from our end.
Further resources on this subject: