Introducing Spring Boot
We go over a quick conceptual introduction to Spring Boot before moving on and developing a REST API using this Java-based framework.
Join the DZone community and get the full member experience.
Join For FreeSetting up an enterprise Spring-based application has become a tedious and error-prone task due to the required bulky configuration along with the complicated dependency management especially if we're talking about applications which make use of several third-party libraries.
Each time you build an enterprise Spring-based application, you have to repeat the same configuration steps:
- Import the required Spring modules based on the type of application you're creating, i.e. Spring MVC, Spring JDBC, Spring ORM.
- Import the web container library (in the case of web applications).
- Import the required third-party libraries (i.e. Hibernate, Jackson), you have to hunt for the compatible versions with the specified Spring version.
- Configure DAO beans such as: data source, transaction management, etc.
- Configure web layer beans such as: resource manager, view resolver.
- Define a starter class which loads all the required configurations.
The above is a routine configuration procedure which should be done each time you create an enterprise Java application based on the Spring framework.
1. Introducing Spring Boot
The Spring team decided they wanted to provide developers with some utilities which relatively automate the configuration procedures and speeds up the process of building and deploying Spring applications, so they invented Spring Boot.
Spring Boot is a utility project which aims to make it easy to build Spring-based, production-ready applications and services with minimum fuss. It provides the shortest way to get a Spring web application up and running with the smallest line of code/configuration out-of-the-box.
2. Spring Boot Features
There are a bunch of features specific to Spring Boot, but three of my favorites are dependency management, auto-configuration, and embedded servlet containers.
2.1. Easy Dependency Management
In order to speed up the dependency management process, Spring Boot implicitly packages the required compatible third-party dependencies for each type of Spring application and exposes them to the developer using starters.
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 technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors.
For example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go (no need to hunt for compatible database drivers and Hibernate libraries).
Also, if you want to create a Spring web application, just add spring-boot-starter-web dependency, and, by default, this will pull all the commonly used libraries for developing Spring MVC applications such as spring-webmvc, jackson-json, validation-api, and Tomcat.
In other words, Spring Boot gathers all the common dependencies and defines them in one place and allows the developer to use them instead of reinventing the wheel each time they create a new application.
Therefore, pom.xml becomes much smaller than the one used with traditional Spring applications.
Check the docs to get familiar with all Spring Boot starters.
2.2. Auto Configuration
The second awesome feature of Spring Boot is the auto-configuration.
After you select the appropriate starter, Spring Boot attempts to automatically configure your Spring application based on the jar dependencies that you have added.
For example, if you add spring-boot-starter-web, Spring Boot automatically configures the commonly registered beans like DispatcherServlet, ResourceHandlers, MessageSource.
Also, if you’re using spring-boot-starter-jdbc, Spring Boot automatically registers the DataSource, EntityManagerFactory, and TransactionManager beans and reads the connection details from the application.properties file.
In case you don't intend to use a database and you don't provide any manual connection details, Spring Boot will auto-configure an in-memory database without any further configuration on your part whenever it finds an H2 or HSQL library on the build path.
This is totally configurable and can be overridden anytime by custom configuration.
2.3 Embedded Servlet Container Support
Each Spring Boot web application includes an embedded web server by default, check this for the list of embedded servlet containers supported out of the box.
Developers don’t need to worry about setting up a servlet container and deploying the application on it. The application can be run by itself as a runnable jar file using its embedded server.
If you need to use a separate HTTP server, you just need to exclude the default dependencies, Spring Boot provides separate starters for HTTP servers to help make this process as easy as possible.
Creating standalone web applications with embedded servers is not only convenient for development but also a legitimate solution for enterprise-level applications, and is increasingly useful in the microservices world. Being able to wrap an entire service (for example, user authentication) in a standalone and fully-deployable artifact that exposes an API makes distribution and deployment much quicker and easier to manage.
3. Spring Boot Requirements
Setting up and running Spring Boot applications requires the following:
- Java 8+
- Spring Framework 5.0.1.RELEASE or above
- Servlet 3.0+ container (in case you don’t make use of the embedded servers).
4. Creating Our First Spring Boot Application
Now let's get into the practical part, we're going to implement a very basic payment API similar to the one we used in the previous Spring tutorial.
We aim to highlight the facilities provided by Spring Boot which makes creating REST APIs way simpler than doing it using the traditional way.
4.1 Create a Maven Web Project
Create a maven web project using this tutorial and name your project SpringBootRestService.
Make sure to use Java 8+ since Spring Boot doesn't work with earlier versions.
4.2 Configure pom.xml
The second step is to configure Spring Boot in pom.xml.
All Spring Boot applications extend from spring-boot-starter-parent, so before defining your dependencies, define the parent starter as follows:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
Now since we're creating a REST API, we're going to use spring-boot-starter-web as a dependency which would implicitly define all the required dependencies like spring-core, spring-web, spring-webmvc, servlet api, and jackson-databind library, so just add the following as a dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
The following jars are automatically imported to your project under Maven Dependencies:
The next step is to add the Spring Boot plugin as follows:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Then define the Spring repositories:
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
The final step is to set the packaging property as a jar, so that Maven generates a runnable jar file on build.
<packaging>jar</packaging>
Here is the full pom.xml file:
<project 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.programmer.gate</groupId>
<artifactId>SpringBootRestService</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
As you notice, by using one dependency we're able to create a fully functional web application.
4.3. Create REST Resources
Now we're going to create our payment controller along with the request and response POJO classes, exactly as we did in the previous tutorial.
Following is the payment request class which should be submitted by clients on each payment request:
package com.programmer.gate;
public class PaymentRequest {
private int userId;
private String itemId;
private double discount;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
And this is the base response returned back from our service:
package com.programmer.gate;
public class BaseResponse {
private String status;
private Integer code;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
And this is our controller:
package com.programmer.gate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/payment")
public class PaymentController {
private final String sharedKey = "SHARED_KEY";
private static final String SUCCESS_STATUS = "success";
private static final String ERROR_STATUS = "error";
private static final int CODE_SUCCESS = 100;
private static final int AUTH_FAILURE = 102;
@RequestMapping(value = "/pay", method = RequestMethod.POST)
public BaseResponse pay(@RequestParam(value = "key") String key, @RequestBody PaymentRequest request) {
BaseResponse response = new BaseResponse();
if(sharedKey.equalsIgnoreCase(key))
{
int userId = request.getUserId();
String itemId = request.getItemId();
double discount = request.getDiscount();
// Process the request
// ....
// Return success response to the client.
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
}
else
{
response.setStatus(ERROR_STATUS);
response.setCode(AUTH_FAILURE);
}
return response;
}
}
4.4 Create the Application Class
This final step is to create the configuration and starter class, Spring Boot supports a new annotation @SpringBootApplication which is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes.
So you just have to create a class annotated with @SpringBootApplication and Spring Boot will enable the auto-configuration and would scan for your resources in the current package:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5. Deploy the Spring Boot Application
Now let's make use of the third awesome feature of Spring Boot which is the embedded server, all we need to do is to just generate a runnable jar file using Maven and run it as a normal standalone application.
- Right click pom.xml -> run-as -> Maven install
- Maven generates a runnable jar file called SpringBootRestService-1.0.jar inside the target folder.
- Open cmd, then run the jar using: java -jar SpringBootRestService-1.0.jar
Here we go, our REST API is up and ready to serve requests at port 8080 by default.
In this tutorial, we introduced Spring Boot features and created a fully working example using the Spring Boot embedded server.
Hope you like it, for clarifications please leave your thoughts in the comments section below.
Opinions expressed by DZone contributors are their own.
Comments