ZetCode

Introduction to Spring Boot

last modified May 23, 2022

This article is an introduction to the Spring Boot framework.

Spring

Spring is a popular Java application framework and Spring Boot is an evolution of Spring that helps create stand-alone, production-grade Spring based applications easily.

Spring Boot is a complete ecosystem for building enterprise applications. It includes many modules to build classic web, reactive applications, and microservices. Spring Boot applications can be developed in Java, Groovy or Kotlin.

The applications can be assembled in Maven or Groovy.

Spring Boot starters

Spring Boot applications are built using starters. Starters are a set of convenient dependency descriptors that you we include in our application. Starters are collections of all Spring and related technologies that helps us quickly set up our applications.

In other words, starters are convenient collections of dependecies. For instance, the spring-boot-starter-data-jdbc is a starter for using Spring Data JDBC.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-mustache'
    runtimeOnly 'mysql:mysql-connector-java'
}

The starters are added to the Maven and Gradle build files.

We can use Spring Initializr to initialize Spring Boot applications. It is availabe as an online service at https://start.spring.io/. It is also possible to use a Spring command line tool.

Spring Boot CLI

The command line tool can be installed with SDKMAN.

$ sdk install springboot
$ spring version
Spring CLI v2.7.0

We install the tool and check its version.

app.groovy
package com.zetcode 

@Component
class App implements CommandLineRunner {

    void run(String... args) throws Exception {
        
        println "This is Spring Boot application"
    }
}

The example is a trivial Groovy console application. Groovy automatically detects and downloads the necessary dependecies.

$ spring run app.groovy 

.   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
'  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::                (v2.7.0)
...
This is Spring Boot application

We run the application.

application.properties
spring.main.banner-mode=off
logging.level.org.springframework=ERROR

The application.properties is the main Spring Boot configuration file. We turn off the banner and change the logging level.

$ spring run app.groovy 
This is Spring Boot application

In the next example, we create a simple web application.

app.groovy
package com.zetcode

@RestController
class MyApp {

    @RequestMapping("/hello")
    String home() {
        "Hello there!"
    }
}

We have a REST application. We map the /hello path to a method which returns a short message.

$ spring run app.groovy

We start the application.

$ curl localhost:8080/hello
Hello there!

With the curl tool, we generate a web request. The default port on which the application listens is 8080.

$ spring run app.groovy -- --server.port=9000

We can change the port by passing the server.port argument to the script.

$ curl localhost:9000/hello
Hello there!

We than have to change the port when we send a request as well.


In the next example, we create a classic web applications with a Mustache template engine.

app.groovy
templates
└── index.mustache

The templates are stored in the templates directory.

app.groovy
package com.zetcode

@Grab(group='org.springframework.boot', module='spring-boot-starter-mustache', version='2.7.0')

import java.time.Instant

@Controller
class MyApp {

    @GetMapping("/")
    String home(Model model) {

        model.addAttribute("now", Instant.now())
        "index"
    }
}

For the home page, we return an HTML response which was build with Mustache.

@Grab(group='org.springframework.boot', module='spring-boot-starter-mustache', version='2.7.0')

We need to hint Groovy the usage of the Mustache template engine.

@Controller
class MyApp {

Classic web applications use the @Controller annotation.

@GetMapping("/")
String home(Model model) {

    model.addAttribute("now", Instant.now())
    "index"
}

The current instant is passed to the template engine via the model. The returned string is the name of the template.

templates/index.mustache
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home page</title>
</head>
<body>

Now: {{ now }}
    
</body>
</html>

A template consists of static and dynamic data. The dynamic data in a Mustache engine is delimited with {{ }}.

Spring Boot Java example

We create a simple Java web REST application.

$ spring init -d web -g com.zetcode --build gradle simple

We initialize the application with spring command line tool. It is going to be a Java application with Gradle build tool.

build.gradle
...
src
├── main
│   ├── java
│   │   └── com
│   │       └── zetcode
│   │           ├── Application.java
│   │           └── controller
│   │               └── MyController.java
│   └── resources
│       ├── application.properties
│       ├── static
│       └── templates
└── test

This is the project structure.

build.gradle
plugins {
    id 'org.springframework.boot' version '2.7.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

This is the Gradle build file. We include the spring-boot-starter-web starter which is used to create both classic ans REST web applications.

resources/application.properties
spring.main.banner-mode=off

In the application.properties file, we turn off the banner.

com/zetcode/controller/MyController.java
package com.zetcode.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    
    @GetMapping(value="/status")
    public ResponseEntity<String> status() {

        return ResponseEntity.ok("OK");
    }

    @GetMapping(value="/hello/{name}/")
    public ResponseEntity<String> hello(@PathVariable String name) {

        var msg = String.format("Hello %s!", name);
        return ResponseEntity.ok(msg);
    }
}

We have two endpoints: /status and /hello/{{name}}/.

@RestController
public class MyController {

To create Restful applications, we use the @RestController annotation.

@GetMapping(value="/status")
public ResponseEntity<String> status() {

    return ResponseEntity.ok("OK");
}

We use ResponseEntity to build HTTP responses.

@GetMapping(value="/hello/{name}/")
public ResponseEntity<String> hello(@PathVariable String name) {

    var msg = String.format("Hello %s!", name);
    return ResponseEntity.ok(msg);
}

We use the @PathVariable annotation to get the value from the path.

com/zetcode/Application.java
package com.zetcode;

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);
    }

}

In the Application, we set up the application.

@SpringBootApplication
public class Application {

With @SpringBootApplication, we initialize the Spring Boot application.

$ ./gradlew bootRun

We start the application.

$ curl localhost:8080/status -i
HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 2
Date: Mon, 23 May 2022 15:54:57 GMT
$ curl localhost:8080/hello/Peter/
Hello Peter!

We generate requests to both endpoints with curl.

In this tutorial, we have introduced the Spring Boot framework.

List all Spring Boot tutorials.