If you're just getting started with Spring Boot or "Spring" in general, start by reading this section. He will give answers to the basic questions “what?”, “how?” and for what?". This section contains an introduction to Spring Boot along with installation instructions. We'll then walk you through creating your first Spring Boot application, covering some basic concepts along the way.

Introduction to Spring Boot

Spring Boot helps you create standalone Spring-based applications that you can then fulfill. We take a subjective view of the Spring platform and third-party libraries so that you can get started with minimal effort. Most Spring Boot applications do not require detailed Spring configuration.

You can use Spring Boot to create Java applications that can be run using the java-jar command or more traditional ones deployment methods through war files. We also provide a command line tool that runs "Spring scripts".

Our main goals are:

  • Provide a radically faster and widely accessible bootstrap experience for any Spring development.

  • Offer your own opinion from the very beginning, but give in if the requirements begin to diverge from the standard ones.

  • Provide a number of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and external configuration).

  • Absolutely no generation code and XML configuration requirements.

Developing your first application using Spring Boot

This section describes developing a small web application "Hello World! ", which demonstrates some of the key features of Spring Boot. We are using Maven to build this project since most IDEs support it.

Website spring.io contains many guides on "getting started" which use Spring Boot. If you need to solve a specific problem, look there first.

You can skip the steps below by going to start .spring.io and selecting the web starter package from the dependency searcher. This will create a new project structure so you can start writing code right away

Before we get started, open a terminal and run the following commands to make sure you have valid versions of Java and Maven:

$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
$ mvn -v
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_102, vendor: Oracle Corporation
This sample must be created in its own directory. The following instructions assume that you have already created a suitable directory and that it is your current directory.

Creating a POM

You must begin by creating a pom.xml file for Maven. pom.xml is a set of rules that is used to build the project. Open your favorite text editor and add the following:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
    </parent>
    <!-- Additional lines will be added here... -->
</project>

The previous listing should allow you to get a working build. You can test it by running mvn package (you can ignore the "jar will be empty - missing content marked for inclusion!" warning for now).

At this point, you can import the project into the IDE (most modern Java IDEs provide built-in Maven support). To keep things simple, we'll continue to use a regular text editor in this example.

Adding dependencies from the classpath

Spring Boot provides a number of "starter packages" that allow you to add jar files to the classpath. Our smoke test applications use spring-boot-starter-parent in the parent section of the POM. spring-boot-starter-parent is a special starter package that provides the default Maven parameters to use. It also provides a dependency management section so that version tags can be omitted for "favorite" dependencies.

Other "starter packages" provide dependencies that, most likely to be needed when developing certain types of applications. Since we are developing a web application, we add a dependency on spring-boot-starter-web. Before that, you can take a look at what we have so far by running the following command:

$ mvn dependency:tree
[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT

The mvn dependency:tree command displays a tree view of the project's dependencies. As you can see, spring-boot-starter-parent itself does not provide any dependencies. To add the required dependencies, edit your pom.xml and add the spring-boot-starter-web dependency just below the parent section:

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

If you run mvn dependency:tree again, you will see that there are now several additional dependencies, including the Tomcat web server and Spring Boot itself.

Writing the code

To complete the application, we need to create one Java file. By default, Maven compiles sources from the src/main/java directory, so you need to create this directory structure and then add a file called src/main/java/MyApplication.java. which will contain the following code:

Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
public class MyApplication {
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Kotlin
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@EnableAutoConfiguration
class MyApplication {
    @RequestMapping("/")
    fun home() = "Hello World!"
}
fun main(args: Array<String>) {
    runApplication<MyApplication>(*args)
}

Although there is not much code a lot, but a lot happens. Let's look at the important elements in the next few sections.

The @RestController and @RequestMapping annotations

The first annotation for our MyApplication class is @RestController. It is known as a stereotypicalabstract. This annotation serves as a hint to people reading the code and to Spring that the class plays a role. In this case, our class is a @Controller for the web, so Spring takes it into account when processing incoming web requests.

The @RequestMapping annotation conveys information about " routing". It tells Spring that any HTTP request with path / should be mapped to the home method. The @RestController annotation tells Spring to print the resulting string back directly to the caller.

@RestController and @RequestMapping are Spring MVC annotations (they are not specific to Spring Boot).

The @EnableAutoConfiguration annotation

The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to "guess" how Spring should be configured based on the jar dependencies you've added. Because spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration tool assumes that you are developing a web application and configures Spring accordingly.

Starter packages and auto-configuration

Auto-configuration is intended to work with "starter packages", but these two concepts are not directly related. You are free to choose jar dependencies outside of the starter packages. Spring Boot will still do its best to auto-configure your application.

The "main" method

The final part of our application is the main method. This is a standard method that follows the Java standard for the application entry point. Our main method delegates authority to the SpringApplication class for Spring Boot by calling run. SpringApplication bootstraps our application by starting Spring, which in turn starts an automatically configured Tomcat web server. We need to pass MyApplication.class as an argument to the run method to tell SpringApplication which Spring bean is the primary one. The args array is also passed to open any command line arguments.

Running the example

At this point, the application should already be running. Since you used a POM with spring-boot-starter-parent, you have a run target that can be used to start the application. Enter mvn spring-boot:run from the project root directory to run the application. You should see output similar to the following:

$ mvn spring-boot:run
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.7.5)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.222 seconds (JVM running for 6.514)

If you open a web browser on localhost:8080, you will see the following message:

Hello World!

To exit the application step by step, click ctrl-c.

Creating an executable jar file

We complete our example by creating a completely self-contained executable jar file that can be executed in a production environment. Executable jars (sometimes called "fat jars") are archives containing compiled classes along with all the jar dependencies that the code needs to run.

Executable jar files and Java

Java does not provide a standard way to load attached jar files (jar files , which themselves are contained inside jar files). This can be a problem if you need to distribute a self-contained application.

To solve this problem, many developers use "uber" jar files. In the uber jar file, all classes from all application dependencies are packaged into one archive. The problem with this approach is that it becomes difficult to understand which libraries are in the application. It can also be a problem if the same file name is used (but with different content) in multiple jar files.

Spring Boot takes a different approach and allows jar files to be attached directly.

To create an executable jar file, we need to add spring-boot-maven-plugin to our pom.xml. To do this, insert the following lines just below the dependencies section:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
POM model spring-boot-starter-parent includes the <executions> configuration for binding the repackage target. If you are not using a parent POM, then you need to declare this configuration yourself.

Save pom.xml and execute mvn package from the command line as follows like this:

$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.7.5:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

If you look in the target directory, you should see myproject-0.0.1-SNAPSHOT.jar there. The file size should be around 10 MB. If you want to look inside, you can use jar tvf as shown below:

$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar

In the target directory there should also be a much smaller file called myproject-0.0.1-SNAPSHOT.jar.original. This is the original jar file that Maven created before it was repackaged by Spring Boot.

To run this application, use the java -jar command as shown below:

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.7.5)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.536 seconds (JVM running for 2.864)

As before, to exit the application, press ctrl-c.