Since its release in 1995, Java has been one of the most popular and widely used pro­gram­ming languages. This object-ori­ent­ated language really shines when it comes to de­vel­op­ing complex business ap­plic­a­tions (both online and offline). Built on the Java Runtime En­vir­on­ment (JRE), these ap­plic­a­tions set them­selves apart by being platform in­de­pend­ent, which makes them available to a par­tic­u­larly wide audience.

Over the past few decades, many frame­works have been developed to simplify working with Java, which provide the user with a ready-to-use basic framework for the Java program being developed. One of the most well-known is the open-source framework Spring, released in 2003, which greatly reduces the com­plex­ity of the standard Java spe­cific­a­tion (“J2EE” or “Java Platform”) as well as the software component En­ter­prise JavaBeans (“EJB”). With the release of Spring Boot further sim­pli­fy­ing the con­fig­ur­a­tion of new Spring projects, this framework has proven to be an excellent and user-friendly option for anyone who does not want to start from scratch when de­vel­op­ing a new Java ap­plic­a­tion.

In this Spring Boot tutorial, you will learn what its re­quire­ments are, as well as how to get started with this modular framework and Spring Boot.

What is Spring Boot?

Released in 2012, Spring Boot is the Java Spring Framework’s con­ven­tion-over-con­fig­ur­a­tion solution that reduces the com­plex­ity of con­fig­ur­ing new Spring projects. Spring Boot does this by defining a basic con­fig­ur­a­tion including rules for use of the framework and all relevant third-party libraries, which allows you to get started on new projects with minimal fuss. This greatly sim­pli­fies the creation of stand-alone, pro­duc­tion-grade, Spring-based ap­plic­a­tions, which is why most new Spring ap­plic­a­tions are also based on Spring Boot.

Spring Boot’s features include:

  • the ability to directly embed web server/container ap­plic­a­tions such as Apache Tomcat or Jetty with no need to deploy WAR files (Web Applic­a­tion Archive);
  • sim­pli­fied Maven con­fig­ur­a­tion due to “starter” POMs (Project Object Models);
  • automatic con­fig­ur­a­tion of Spring whenever possible, and;
  • the provision of non-func­tion­al features such as metrics and ex­ter­n­al­ised con­fig­ur­a­tion.

Through Spring Boot, the de­vel­op­ment company Pivotal Software has given the framework – which was released in 2005 – a modern, future-ori­ent­ated touch. This extension benefits from the Spring Framework’s basic tech­no­logy which has been developed over many years and in­cor­por­ated into Spring Boot. For more in­form­a­tion on the open-source framework (Apache License 2.0), please read our in-depth article about this popular basic Java framework.

Spring Boot Tutorial: Re­quire­ments, in­stall­a­tion, and getting started

Since adding Spring Boot to Spring, Pivotal Software’s software has been con­sidered one of the best solutions for de­vel­op­ing mi­croservices in Java. Due to the 20 or so modules in the basic framework which can be combined as needed, Spring Boot is also useful for a variety of other situ­ations in which it can neither be spe­cific­ally defined as a framework for web ap­plic­a­tions nor as a standard solution for desktop apps.

Before we go into more detail in the following Spring Boot tutorial about con­fig­ur­ing and creating new projects or the initial Spring Boot structure, let us first take a look at the technical re­quire­ments and setup for the necessary project com­pon­ents.

What are Spring Boot’s system re­quire­ments?

Spring Boot revolves around Java, so the Java Runtime En­vir­on­ment (Java Platform) is the main software component needed to get the framework up and running. Since you are not only running the ap­plic­a­tion but also using it for de­vel­op­ment with Java, you will need version 8 (or 1.8) or higher of the Java De­vel­op­ment Kit (JDK). In addition to the runtime en­vir­on­ment, this kit contains useful tools for pro­gram­ming and testing Java ap­plic­a­tions. It is available for Linux, Windows, and macOS, so you can use any operating system.

Naturally, Spring Boot also requires you to have the current version of the Spring Framework installed on your system.

You can use either Maven (3.3 or higher) or Gradle (4.4 or higher) as a build tool.

If you want to use the option to integrate a web server that runs your Java ap­plic­a­tion on a servlet, you have three options: Apache Tomcat (9.0 or higher), Jetty (9.4 or higher), or Undertow (2.0 or higher).

How to create your first Spring Boot project

You can use Spring Boot just like any standard Java library by including the ap­pro­pri­ate JAR (Java Archive) or WAR files (Web Ap­plic­a­tion Archive) in the classpath. Java uses this path to search for ex­ecut­able files in the file system. There are two ways to create archive files for Spring Boot:

  • You can install and use Maven or Gradle to create the project framework, including the required de­pend­en­cies, on your own.
  • You can access the Spring Ini­tial­izr web service, use it to create your Spring Boot setup, and then download it as a finished project template.

What sets the latter solution apart is that you can create JAR files through a user-friendly web interface which greatly sim­pli­fies the process. Since the Ini­tial­izr also uses Maven or Gradle to generate files, the result is no different from the manual route. For this Java Spring Boot tutorial, we have therefore decided to use the web assistant that can be accessed at start.spring.io.

Note

If you choose to use Spring Ini­tial­izr, you will need to have Java and either Maven or Gradle installed to work on your Spring Boot ap­plic­a­tion.

Once you have opened Spring Ini­tial­izr, you can define your preferred prop­er­ties for your first Spring Boot ap­plic­a­tion in the following order: First, define the build system by selecting either “Maven Project” or “Gradle Project”. On the second line, you can choose between using standard Java or another language in the Java family such as Kotlin or Groovy. Further down, you can define the version of Spring Boot, the project’s metadata (including the version of Java) as well as all relevant de­pend­en­cies (such as databases, security features, web in­ter­faces, and cloud services). Finally, click on “Generate Project” to create the project files.

Tip

If you want to create your Spring Boot project on your own with Maven or Gradle, you can refer to the in­stall­a­tion in­struc­tions found in the official online manuals.

Running an assembled Spring Boot project

Spring Ini­tial­izr allows you to download the generated project files in a ZIP archive file which will need to be unpacked afterward. In the unpacked folder, you will find the re­spect­ive con­fig­ur­a­tion file, among other things. This is the build.gradle file if you selected Gradle for build man­age­ment or pom.xml if you selected Maven. If you selected Maven (which also fits our steps for the Spring Boot tutorial), the content of the con­fig­ur­a­tion file will look something like this:

Using the ap­pro­pri­ate build software, you can create an ex­ecut­able Spring Boot ap­plic­a­tion from these archive files. If you are using Maven, you can do this by opening the terminal or command prompt window and running the following command in the target folder (i.e. the folder for your Spring Boot files):

mvn clean install

For Gradle projects, use the following command:

gradle clean build

In either case, you should receive the message “BUILD SUCCESS” once the command has been fully processed and the archive files have been suc­cess­fully created. The ex­ecut­able file is stored in the folder “target” (for Maven) or under “build/libs” (for Gradle). In our example, the JAR file is named “demo-0.0.1-SNAPSHOT.jar”:

You can run it using Java by typing the following command:

java -jar demo-0.0.1-SNAPSHOT.jar

The name of the JAR file, it­alicised in the code example, should be replaced if it differs from the one mentioned here. You can now see whether the Spring Boot ap­plic­a­tion was launched suc­cess­fully by looking at the output displayed in the command line. If you have in­teg­rated one of the pre­vi­ously mentioned web servers such as Tomcat, it will also be launched. You can access it with any browser by using the following address:

http://localhost:8080

Con­nect­ing Spring Boot to the database and data source

Spring Boot provides world-class support for creating and in­teg­rat­ing data sources into any SQL or NoSQL database. There is no need to write any ad­di­tion­al code to create a new data source. All you need to do is add the necessary de­pend­en­cies and con­fig­ur­a­tion details. You can do this by using the standard database interface JDBC (Java Database Con­nectiv­ity). This requires you to first create a starter entry in the con­fig­ur­a­tion file if you did not add the de­pend­ency when you initially created the project with Spring Ini­tial­izr (the same applies to adding any ad­di­tion­al de­pend­en­cies).

To do so, Maven users need to add the following lines of code to the pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Gradle users, on the other hand, need to add this code to the build.gradle file:

compile('org.springframework.boot:spring-boot-starter-jdbc')
Note

You can open the re­spect­ive con­fig­ur­a­tion file with any standard code editor. It is important to note that the file needs to be saved in its original XML or Gradle format after the changes have been made.

Next, you add the de­pend­ency for the required database man­age­ment system to your build con­fig­ur­a­tion file. In this Spring Boot tutorial, we connect our ap­plic­a­tion to a MySQL database that we want to use for our ap­plic­a­tion and have installed be­fore­hand.

For Maven projects, the pom.xml file will need the following entry to this end:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

For Gradle projects, you will have to add the following lines of code to connect to the MySQL database:

compile('mysql:mysql-connector-java')

Then, you need to add some prop­er­ties in the “ap­plic­a­tion” prop­er­ties file. This file can be found under the path \src\main\resources in the Spring Boot project directory. Open this text file and add the following con­fig­ur­a­tion code:

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.tomcat.testOnBorrow = true
spring.datasource.tomcat.testWhileIdle = true
spring.datasource.tomcat.timeBetweenEvictionRunsMillis = 60000
spring.datasource.tomcat.minEvictableIdleTimeMillis = 30000
spring.datasource.tomcat.validationQuery = SELECT 1
spring.datasource.tomcat.max-active = 15
spring.datasource.tomcat.max-idle = 10
spring.datasource.tomcat.max-wait = 8000

Now you can use MySQL as you normally would to create a database which includes the required data tables, if you have not already done so. Beginners can find more in­form­a­tion about how to use re­la­tion­al database man­age­ment systems in our com­pre­hens­ive MySQL tutorial.

Gen­er­at­ing an SSL/TLS cer­ti­fic­ate and ac­tiv­at­ing HTTPS

When you create a Spring Boot ap­plic­a­tion, it will use the unsecured HTTP protocol and TCP port 8080 by default to connect to its web server. To change the default to the secure HTTPS and TCP port 443, you will need an SSL/TLS cer­ti­fic­ate as well as the ap­pro­pri­ate prop­er­ties in the “ap­plic­a­tion” prop­er­ties file.

You can obtain the cer­ti­fic­ate from a cer­ti­fic­a­tion authority or by creating a self-signed cer­ti­fic­ate using the Java Runtime En­vir­on­ment. To create a cer­ti­fic­ate, you can use the Man­age­ment Utility Key Tool. This is a command line tool that allows you to easily create PKCS12 keystore files (con­tain­ing an X.509 cer­ti­fic­ate and a private key) for servers such as Tomcat, Exchange, IIS, and others. For example, if you were to use a Tomcat server, you would need to enter the following command into the command prompt window or terminal to generate the keystore file for your Spring Boot ap­plic­a­tion:

keytool -genkeypair -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

For cer­ti­fic­ate au­then­tic­a­tion, you then add a unique password and provide some personal in­form­a­tion about yourself, your company, and your location.

If you are unsure what your country code is, you can look it up on the website ISO 3166 codes.

The keystore file is then auto­mat­ic­ally stored in the directory in which you executed the command (which is your own user directory in this Spring Boot tutorial). Copy and paste the keystore file into your Spring Boot ap­plic­a­tion’s directory and add the following lines of code to the “ap­plic­a­tion” prop­er­ties file that was needed for database in­teg­ra­tion:

server.port = 443
server.ssl.key-store = C:/demo/keystore.p12
server.ssl.key-store-password = springboot
server.ssl.key-store-type = PKCS12
server.ssl.key-alias = tomcat

Lastly, use the following command to create a new ex­ecut­able JAR file that connects as con­figured via HTTPS to Tomcat:

mvn -Dmaven.test.skip=true -DskipTests=true clean install

Sim­pli­fy­ing Spring Boot app debugging using Spring Cloud Sleuth and Zipkin

Con­duct­ing regular tests is crucial in software de­vel­op­ment. This is the only way to catch and correct all pro­gram­ming errors. However, analysing log files is typically very com­plic­ated, often making the debugging process quite la­bouri­ous, es­pe­cially with mi­croservices. This is why we shall conclude this Spring Boot tutorial by setting up the tracing systems Spring Cloud Sleuth and Zipkin to fully monitor the Spring Boot ap­plic­a­tion.

Using these two tracing ap­plic­a­tions, you can easily track all requests through a pre-con­figured REST con­trol­ler as well as timing in­form­a­tion.

Step 1: Add Spring Cloud Sleuth to your project

First, integrate the Sleuth module into your Spring Boot ap­plic­a­tion by adding the de­pend­ency in the build con­fig­ur­a­tion file. If you are using Maven, add the following code to the pom.xml file:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
    <version>${spring-cloud-sleuth.version}</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

If it is a Gradle project, add the following lines of code to the con­fig­ur­a­tion file:

compile('org.springframework.cloud:spring-cloud-starter-sleuth')

Step 2: Integrate the Sleuth logs into the REST con­trol­ler’s class file

Your Spring Boot ap­plic­a­tion’s REST con­trol­ler must now be con­figured to process Sleuth logs as required. To do so, add the con­fig­ur­a­tion text to the con­trol­ler’s .class file – the package name (spring-boot-tutorial in this example) cor­res­ponds to the domain of the <groupId> in the pom.xml file:

package spring-boot-tutorial.sleuth;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SleuthappApplication {
    private static final Logger LOG = Logger.getLogger(SleuthappApplication.class.getName());
    public static void main(String[] args) {
        SpringApplication.run(SleuthappApplication.class, args);
    }
    @RequestMapping("/")
    public String index() {
        LOG.log(Level.INFO, "Index API is calling");
        return "Sleuth: Spring-Boot-Tutorial-Test!";
    }
}

Step 3: Add the Spring ap­plic­a­tion’s name to the prop­er­ties

To ensure that the name of the Spring Boot ap­plic­a­tion is displayed correctly in Zipkin, you should enter the name in the “ap­plic­a­tion” prop­er­ties file. If you are going to save the con­fig­ur­a­tion to the Spring Cloud Con­fig­ur­a­tion Server, you should also enter it in the “bootstrap” prop­er­ties file:

spring.application.name = Spring-Boot-Tutorial-App

Step 4: Add Zipkin to your project

The open-source software Zipkin helps to monitor and manage the Sleuth logs, providing a user interface and a server component. Both are added to the de­pend­en­cies of the re­spect­ive build con­fig­ur­a­tion file. Maven users need to add the following code to the pom.xml file:

<dependency>
    <groupId>io.zipkin.java</groupId>
    <artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
    <groupId>io.zipkin.java</groupId>
    <artifactId>zipkin-autoconfigure-ui</artifactId>
<scope>runtime</scope>
</dependency>

If it is a Gradle project, the new lines of code will look like this:

compile('io.zipkin.java:zipkin-autoconfigure-ui')
compile('io.zipkin.java:zipkin-server')

Step 5: Enable the ap­plic­a­tion to act as a Zipkin server

The next step is to ensure that your Spring Boot project can act as a Zipkin server. To do this, create a file named zipkin.prop­er­ties and add the following lines of code to it:

spring.application.name=zipkin
server.port=9411
logging.level.org.springframework.web=debug

Then, activate the server component in the project’s Java file:

package spring-boot-tutorial.zipkin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import zipkin.server.EnableZipkinServer;
@SpringBootApplication
@EnableZipkinServer
public class ZipkinappApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZipkinappApplication.class, args);
    }
}

If you create the ex­ecut­able JAR file as you normally would and then run the ap­plic­a­tion, the Zipkin server can be accessed using the address http://localhost:9411/zipkin.

Step 6: Add a Spring Cloud Zipkin de­pend­ency

Add one last de­pend­ency to the build con­fig­ur­a­tion file to connect Sleuth and Zipkin:

Maven:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>

Gradle:

compile('org.springframework.cloud:spring-cloud-sleuth-zipkin')

Step 7: Configure the Sleuth logs to export to the Zipkin server

Add the Al­ways­Sampler object (Bean) to your Spring Boot ap­plic­a­tion’s Java file to enable Sleuth logs to be auto­mat­ic­ally exported to the Zipkin server:

@Bean
public AlwaysSampler defaultSampler() {
    return new AlwaysSampler();
}

Step 8: Enter the base URL for the Zipkin server in the ap­plic­a­tion prop­er­ties

In this last step, enter the base URL for the Zipkin server in the ap­plic­a­tion prop­er­ties by once again opening your Spring Boot project’s prop­er­ties file and adding the following code:

spring.zipkin.baseUrl = http://localhost:9411/zipkin/
Go to Main Menu