Spring Boot Fundamentals
Relevant source files
The following files were used as context for generating this wiki page:- complete/src/main/java/com/example/restservice/RestServiceApplication.java
- complete/pom.xml
- complete/src/main/java/com/example/restservice/GreetingController.java
- complete/src/main/java/com/example/restservice/Greeting.java
- complete/src/test/java/com/example/restservice/GreetingControllerTests.java
- README.adoc
This document outlines the fundamental concepts of building a RESTful web service using Spring Boot, as demonstrated by the gs-rest-service project. The project serves as a "Hello, World" example, creating a service that responds with a JSON greeting. It showcases core Spring Boot features such as the application entry point, dependency management, REST controllers, and data modeling.
The service exposes a single endpoint, /greeting, which accepts an optional name parameter to customize the response. This simple yet complete application provides a clear basis for understanding how Spring handles web requests, data serialization, and application configuration with minimal setup.
Project Structure and Dependencies
The project is configured as a standard Maven project. The core dependencies and project metadata are defined in the pom.xml file. It uses spring-boot-starter-parent to manage dependency versions and provide sensible defaults.
Sources: complete/pom.xml:5-10
Key Dependencies
The application relies on two primary Spring Boot starters:
| Group ID | Artifact ID | Scope | Description |
|---|---|---|---|
org.springframework.boot | spring-boot-starter-web | compile | Provides all necessary dependencies for building web applications, including a RESTful service. It includes Spring MVC, an embedded Tomcat server, and Jackson for JSON serialization. |
org.springframework.boot | spring-boot-starter-test | test | Includes libraries for testing Spring Boot applications, such as JUnit 5, Spring Test, and Mockito. |
Sources: complete/pom.xml:21-31
The project also specifies Java version 17 and uses the spring-boot-maven-plugin to create an executable JAR file.
Sources: complete/pom.xml:19, complete/pom.xml:35-38
Application Entry Point
The application is launched via the RestServiceApplication class. This class contains the main method, which is the standard entry point for a Java application.
Sources: complete/src/main/java/com/example/restservice/RestServiceApplication.java:10-12
// complete/src/main/java/com/example/restservice/RestServiceApplication.java:7-13
@SpringBootApplication
public class RestServiceApplication {
public static void main(String[] args) {
SpringApplication.run(RestServiceApplication.class, args);
}
}
The class is annotated with @SpringBootApplication, a convenience annotation that adds all of the following:
@Configuration: Tags the class as a source of bean definitions for the application context.@EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.@ComponentScan: Tells Spring to look for other components, configurations, and services in thecom.example.restservicepackage.
The SpringApplication.run() method bootstraps and launches the Spring application, starting the auto-configured Tomcat web server.
The following diagram illustrates the application startup process.
RESTful Web Service Components
The service is composed of a data model (resource representation) and a controller that handles HTTP requests.
Resource Representation (Data Model)
The Greeting class is a Java record used to model the data in the response body. A record is a concise way to create immutable data carrier classes.
Sources: complete/src/main/java/com/example/restservice/Greeting.java:3
// complete/src/main/java/com/example/restservice/Greeting.java:3
public record Greeting(long id, String content) { }
This record defines two fields:
id: A unique identifier for the greeting.content: The textual representation of the greeting.
Spring Boot uses the Jackson JSON library, included with spring-boot-starter-web, to automatically serialize instances of Greeting into JSON for the HTTP response.
Sources: README.adoc:70-72
Resource Controller
The GreetingController class is responsible for handling incoming HTTP requests.
Sources: complete/src/main/java/com/example/restservice/GreetingController.java
The class diagram below shows the relationship between the controller and the data model.
Key annotations and components:
@RestController: This annotation marks the class as a controller where every method returns a domain object instead of a view. It is a shorthand for including both@Controllerand@ResponseBody.@GetMapping("/greeting"): This maps HTTP GET requests for the/greetingpath to thegreeting()method.@RequestParam: This binds the value of thenamequery string parameter to thenamemethod parameter. If the parameter is not present, it uses adefaultValueof "World".AtomicLong counter: A thread-safe counter used to generate uniqueidvalues for each greeting.
Sources: complete/src/main/java/com/example/restservice/GreetingController.java:9-16
API Endpoint: /greeting
The service exposes a single GET endpoint.
| Method | Path | Parameter | Type | Default | Description | Response |
|---|---|---|---|---|---|---|
GET | /greeting | name (optional) | String | "World" | Provides a name to include in the greeting message. | A JSON object of type Greeting. |
Sources: README.adoc:10-25, complete/src/main/java/com/example/restservice/GreetingController.java:14-16
The sequence diagram below shows the flow of a request to the /greeting endpoint.
Testing the Service
The GreetingControllerTests class provides integration tests for the controller. It uses @SpringBootTest to load a full application context and @AutoConfigureMockMvc to configure a MockMvc instance for sending mock HTTP requests.
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java:28-29
Two test cases are defined:
noParamGreetingShouldReturnDefaultMessage(): Sends a GET request to/greetingwithout any parameters and asserts that the response status is OK and the JSON content is "Hello, World!".paramGreetingShouldReturnTailoredMessage(): Sends a GET request to/greetingwith thenameparameter set to "Spring Community" and asserts that the response status is OK and the JSON content is "Hello, Spring Community!".
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java:34-46
// complete/src/test/java/com/example/restservice/GreetingControllerTests.java:34-38
@Test
public void noParamGreetingShouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.content").value("Hello, World!"));
}
Summary
This project demonstrates the fundamental building blocks of a Spring Boot RESTful web service. It highlights the power of Spring's auto-configuration and starter dependencies to create a production-ready, standalone web application with minimal code. Key takeaways include the use of @SpringBootApplication to bootstrap the application, @RestController to define endpoints, automatic JSON serialization with Jackson, and a straightforward testing approach using MockMvc.