The basics of Spring Boot
Building a Hello World REST application
Tools for accessing REST applications
One of the Spring Framework’s goals is to reduce plumbing code so that developers can focus their efforts on implementing core business logic. However, as the Spring Framework evolved and added several subprojects to its portfolio, developers ended up spending a considerable amount of time setting up projects, finding project dependencies, and writing boiler plate code and configuration.
Spring Boot, a Spring portfolio project, aims at simplifying Spring application bootstrapping by providing a set of starter project templates. These would pull all the proper dependencies that are needed based on project capabilities. For example, if you enable JPA capability, it automatically includes all the dependent JPA, Hibernate, and Spring JAR files.
Spring Boot also takes an opinionated approach and provides default configuration that simplifies application development quite a bit. For example, if Spring Boot finds JPA and MySQL JARs in the classpath, it would automatically configure a JPA Persistence Unit. It also enables creation of standalone Spring applications with embedded Jetty/Tomcat servers, making them easy to deploy on any machine with just Java installed. Additionally, it provides production-ready features such as metrics and health checks. Throughout this book, we will be exploring and learning these and additional features of Spring Boot.
Spring Roo is another Spring portfolio project that attempts to provide rapid Spring application development. It provides a command line tool that enables easy project bootstrapping and generates code for components such as JPA entities, web controllers, test scripts, and necessary configuration. Although there was a lot of initial interest in the project, Spring Roo never really became mainstream. AspectJ code generation and a steep learning curve coupled with its attempt to take over your project are some reasons for lack of its adoption. Spring Boot, by contrast, takes a different approach; it focuses on jump-starting the project and providing clever, sensible, default configuration. Spring Boot doesn’t generate any code that makes it easy to manage your project.
Generating a Spring Boot Project
Use Spring Boot’s starter website (http://start.spring.io).
Use the Spring Tool Suite (STS) IDE.
Use the Boot command line interface (CLI).
We will explore all three alternatives in this chapter. However, for the rest of the book, we will be opting for the Boot CLI to generate new projects. Before we start with project generation, it is important that Java is installed on your machine. Spring Boot requires that you have Java SDK 1.8 or higher installed. In this book we will be using Java 1.8.
Installing a Build Tool
- 1.
Download the latest Maven binary from https://maven.apache.org/download.cgi. At the time of writing this book, the current version of Maven was 3.8.1. For Windows, download the apache-maven-3.8.1-bin.zip file.
- 2.
Unzip the contents of the zip file under C: oolsmaven.
- 3.
Add an Environment variable M2_HOME with value C: oolsmavenapache-maven-3.8.1. This tells Maven and other tools where Maven is installed. Also make sure that the JAVA_HOME variable is pointing to the installed JDK.
- 4.
Append the value %M2_HOME%in to the Path environment variable. This allows you to run Maven commands from the command line.
- 5.
Open a new command line and type the following:
To learn more about Maven, refer to Introducing Maven, published by Apress (http://www.apress.com/9781484208427).
Generating a Project Using start.spring.io
- 1.
Launch the http://start.spring.io website in your browser and enter the information shown in Figure 3-2.
- 2.
Under Dependencies ➤ Web, select the option “Web” and indicate that you would like Spring Boot to include web project infrastructure and dependencies.
- 3.
Then hit the “Generate Project” button. This will begin the hello-rest.zip file download.
A quick look at the hello-rest contents shows that we have a standard Maven-based Java project layout. We have the srcmainjava folder, which houses Java source code; srcmain esources, which contains property files; static content, such as HTMLCSSJS files; and the src estjava folder, which contains the test cases. On running a Maven build, this project generates a JAR artifact. Now, this might be a little confusing for the first-timer who is used to WAR artifacts for deploying web applications. By default, Spring Boot creates standalone applications in which everything gets packaged into a JAR file. These applications will have embedded servlet containers such as Tomcat and are executed using a good old main() method.
Spring Boot also allows you to work with WAR artifacts which contain html, css, js, and other files necessary for the development of web applications that can be deployed to external Web and application containers.
hello-rest pom.xml file Contents
The groupId, artifactId, and version elements in the pom.xml file correspond to Maven’s standard GAV coordinates describing our project. The parent tag indicates that we will be inheriting from the spring-boot-starter-parent POM. This ensures that our project inherits Spring Boot’s default dependencies and versions. The dependencies element lists two POM file dependencies: spring-boot-starter-web and spring-boot-starter-test. Spring Boot uses the term starter POMs to describe such POM files.
Spring Boot Starter Modules
Starter POM dependency | Use |
---|---|
spring-boot-starter | Starter that brings in core dependencies necessary for functions such as auto-configuration support and logging |
spring-boot-starter-aop | Starter that brings in support for aspect-oriented programming and AspectJ |
spring-boot-starter-test | Starter that brings in dependencies such as JUnit, Mockito, and spring-test necessary for testing |
spring-boot-starter-web | Starter that brings in MVC dependencies (spring-webmvc) and embedded servlet container support |
spring-boot-starter-data-jpa | Starter that adds Java Persistence API support by bringing in spring-data-jpa, spring-orm, and Hibernate dependencies |
spring-boot-starter-data-rest | Starter that brings in spring-data-rest-webmvc to expose repositories as REST API |
spring-boot-starter-hateoas | Starter that brings in spring-hateoas dependencies for HATEOAS REST services |
spring-boot-starter-jdbc | Starter for supporting JDBC databases |
Finally, the spring-boot-maven-plugin contains goals for packaging the application as an executable JAR/WAR and running it.
@Configuration—Marks the annotated class as containing one or more Spring bean declarations. Spring processes these classes to create bean definitions and instances.
@ComponentScan—This class tells Spring to scan and look for classes annotated with @Component, @Service, @Repository, @Controller, @RestController, and @Configuration. By default, Spring scans all the classes in the package where the @ComponentScan annotated class resides. To override the default behavior, we can set this annotation in the configuration class and define basePackages argument as the name of the package.
@EnableAutoConfiguration—Enables Spring Boot’s auto-configuration behavior. Based on the dependencies and configuration found in the classpath, Spring Boot intelligently guesses and creates bean configurations.
HelloWorldRestApplication Contents
The main() method simply delegates the application bootstrapping to SpringApplication’s run() method. run() takes a HelloWorldRestApplication.class as its argument and instructs Spring to read annotation metadata from HelloWorldRestApplication and populate ApplicationContext from it.
Hello REST Endpoint
The Spring Initializr application hosted at http://start.spring.io itself is built using Spring Boot. You can find the source code of this application on GitHub at https://github.com/spring-io/initializr. It is also possible for you to build and host your own instances of the Initializr application.
In addition to providing a web interface, the Initializr provides an HTTP endpoint that provides similar project generation capability. In fact, Spring Boot’s CLI and IDEs such as STS use this HTTP endpoint behind the scenes for generating projects.
Generating a Project Using STS
Spring Tool Suite or STS is a free Eclipse-based development environment that provides great tooling support for developing Spring-based applications. You can download and install the latest version of STS from Pivotal’s website at https://spring.io/tools. At the time of writing this book, the current version of STS was 4.11.0.
- 1.
Launch STS if you haven’t already done so. Go to File ➤ New and click Spring Starter Project, as shown in Figure 3-5.
- 2.
In the following screen, enter the information as shown in Figure 3-6. Enter Maven’s GAV information. Hit Next.
- 3.
In the following screen, enter the information as shown in Figure 3-7. Select the web starter option. Hit Next.
- 4.
On the following screen, change the location where you would like to store the project. The “Full Url” area shows the HTTP REST endpoint along with the options that you selected (see Figure 3-8).
- 5.
Hit the Finish button and you will see the new project created in STS. The contents of the project are similar to the project that we created earlier (see Figure 3-9).
STS’s starter project wizard provides a convenient way to generate new Spring Boot projects. The newly created project automatically gets imported into the IDE and is immediately available for development.
Generating a Project Using the CLI
- 1.
Download the latest version of the CLI ZIP distribution from Spring’s website at https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started.html#getting-started.installing.cli. At the time of writing this book, the current version of CLI was 2.5.3. This version can be downloaded directly from https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.5.3/spring-boot-cli-2.5.3-bin.zip.
- 2.
Extract the zip file and place its contents (folders such as bin and lib) under C: oolsspringbootcli, as shown in Figure 3-10.
- 3.
Add a new environment variable SPRING_HOME with value c: oolsspringbootcli.
- 4.
Edit the Path environment variable, and add the %SPRING_HOME%/bin value to its end.
- 5.
Open a new command line and verify the installation running the following command:
Boot CLI Output
Accessing REST Applications
There are several free and commercial tools that allow you to access and experiment with REST API/applications. In this section we will look at some of the popular tools that allow you to quickly test a request and inspect the response.
Postman
Postman is a Chrome browser extension for making HTTP requests. It offers a plethora of features that makes it easy to develop, test, and document a REST API. A Chrome app version of Postman is also available that provides additional features such as bulk uploading that are not available in the browser extension.
Postman can be downloaded and installed from the Chrome Web Store. To install Postman, simply launch the Chrome browser and navigate to https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop. You might be asked to log in to your Google Chrome account and confirm using the “New app” installation dialog. On completion of the installation, you should be able to locate and launch Postman using the “Apps icon” in the Bookmarks bar or by typing chrome://apps/shortcut. Figure 3-10 shows Postman launched in the Chrome browser.
RESTClient
RESTClient is a Firefox extension for accessing REST APIs and applications. Unlike Postman, RESTClient doesn’t have a lot of bells and whistles, but it provides basic functionality to quickly test a REST API. To install RESTClient, launch the Firefox browser and navigate to the URL https://addons.mozilla.org/en-US/firefox/addon/restclient/. Then click the “+ Add to Firefox” button, and in the following “Software Installation” dialog, click the “Install Now” button.
Summary
Spring Boot provides an opinionated approach to building Spring-based applications. In this chapter, we looked at Spring Boot’s features and used it to build a Hello World REST application. We also looked at the Postman and RESTClient tools for testing and exploring the REST API.
In the next chapter, we will begin working on a more complex REST application and discuss the process of identifying and designing resources.