Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
Here's a simple example of creating a RESTful web service using Spring Boot:
You can use Spring Initializr to bootstrap a new Spring Boot application. Select Web as a dependency, which will include spring-boot-starter-web
.
If you're setting it up manually, add the following dependency to your pom.xml
:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
For this example, let's create a simple Book
model.
public class Book { private Long id; private String title; private String author; // Constructors, getters, setters, etc. }
We'll create a simple REST controller to handle CRUD operations for Book
.
import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; @RestController @RequestMapping("/api/books") public class BookController { private final List<Book> books = new ArrayList<>(); private final AtomicLong counter = new AtomicLong(); @GetMapping public List<Book> getAllBooks() { return books; } @GetMapping("/{id}") public Book getBook(@PathVariable Long id) { return books.stream().filter(book -> book.getId().equals(id)).findFirst().orElse(null); } @PostMapping public Book addBook(@RequestBody Book book) { book.setId(counter.incrementAndGet()); books.add(book); return book; } @PutMapping("/{id}") public Book updateBook(@PathVariable Long id, @RequestBody Book book) { Book existingBook = getBook(id); if (existingBook != null) { existingBook.setTitle(book.getTitle()); existingBook.setAuthor(book.getAuthor()); } return existingBook; } @DeleteMapping("/{id}") public void deleteBook(@PathVariable Long id) { books.removeIf(book -> book.getId().equals(id)); } }
Create the main Spring Boot application class to run the application.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RestExampleApplication { public static void main(String[] args) { SpringApplication.run(RestExampleApplication.class, args); } }
Run the RestExampleApplication
class, and your Spring Boot application will start.
Once the application is up and running, you can use tools like Postman or simply a web browser to test the endpoints:
GET http://localhost:8080/api/books
GET http://localhost:8080/api/books/{id}
POST http://localhost:8080/api/books
with JSON payload.PUT http://localhost:8080/api/books/{id}
with JSON payload.DELETE http://localhost:8080/api/books/{id}
This is a basic introduction to creating a RESTful web service using Spring Boot. In a real-world scenario, you might also involve a database, use Spring Data JPA for data access, add validation, exception handling, etc.
Creating a simple REST service with Spring Boot:
// Example REST controller in Spring Boot @RestController public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } }
Configuring REST endpoints in Spring Boot:
@RequestMapping
or more specific annotations like @GetMapping
, @PostMapping
, etc.// Example using @RequestMapping @RestController @RequestMapping("/api") public class MyController { @GetMapping("/resource") public String getResource() { return "This is a resource."; } }
Request mapping and HTTP methods in Spring Boot REST:
@RequestMapping
to map HTTP methods to specific controller methods. Use more specific annotations like @GetMapping
for better clarity.// Example using @GetMapping @RestController public class UserController { @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { // Logic to fetch user by id } }
CRUD operations with Spring Boot RESTful services:
// Example CRUD operations in a Spring Boot RESTful service @RestController @RequestMapping("/api/users") public class UserController { // GET: Retrieve all users // POST: Create a new user // GET: Retrieve a user by ID // PUT: Update a user by ID // DELETE: Delete a user by ID }
Exception handling in Spring Boot REST APIs:
@ExceptionHandler
or @ControllerAdvice
.// Example exception handling in Spring Boot @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); } }
Versioning strategies for RESTful APIs in Spring Boot:
// Example URI versioning @GetMapping("/api/v1/users") public List<User> getAllUsersV1() { // ... } @GetMapping("/api/v2/users") public List<User> getAllUsersV2() { // ... }
Securing Spring Boot REST services with authentication and authorization:
// Example security configuration in Spring Boot @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // Configure authentication and authorization }
Testing and documenting REST APIs in Spring Boot:
@WebMvcTest
. Document APIs using tools like Swagger or Springdoc.// Example testing with JUnit and Spring's MockMvc @RunWith(SpringRunner.class) @WebMvcTest(UserController.class) public class UserControllerTests { // Test methods }