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
Creating a simple RestController
in Spring Boot is straightforward. Here's a step-by-step guide:
If you haven't already, initialize a new Spring Boot project using Spring Initializr with the "Web" dependency.
For the sake of this example, let's assume you want to create a simple Book
model.
public class Book { private Long id; private String title; private String author; // Constructors, getters, setters, etc. }
Next, you'll create the RestController
to provide the API endpoints for the Book
model:
import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/api/books") public class BookController { // For the sake of this simple example, we're using an in-memory list. // In a real-world application, this would be replaced with a database. private List<Book> books = new ArrayList<>(); @GetMapping public List<Book> getAllBooks() { return books; } @GetMapping("/{id}") public Book getBookById(@PathVariable Long id) { return books.stream() .filter(book -> book.getId().equals(id)) .findFirst() .orElse(null); // Or throw an exception } @PostMapping public Book addBook(@RequestBody Book book) { books.add(book); return book; } @PutMapping("/{id}") public Book updateBook(@PathVariable Long id, @RequestBody Book updatedBook) { Book existingBook = getBookById(id); if (existingBook != null) { existingBook.setTitle(updatedBook.getTitle()); existingBook.setAuthor(updatedBook.getAuthor()); } return existingBook; // Or throw an exception if not found } @DeleteMapping("/{id}") public void deleteBook(@PathVariable Long id) { books.removeIf(book -> book.getId().equals(id)); } }
Run your application's main class (the one annotated with @SpringBootApplication
).
Once your application is running, you can use tools like Postman or curl
to make requests to your RESTful API:
GET http://localhost:8080/api/books
GET http://localhost:8080/api/books/{id}
POST http://localhost:8080/api/books
with a JSON bodyPUT http://localhost:8080/api/books/{id}
with a JSON bodyDELETE http://localhost:8080/api/books/{id}
Remember, this is a very basic example without persistence in a database, error handling, or any other advanced features. In real-world scenarios, you would typically integrate with a service layer, a database, handle exceptions properly, and add validation and security mechanisms.
Configuring Spring Boot for RESTful API development:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Building a basic RESTful endpoint with @RestController in Spring Boot:
@RestController
annotation in Spring Boot.@RestController public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, World!"; } }
Mapping HTTP methods (GET, POST, etc.) in Spring Boot RestController:
@RestController
.@RestController @RequestMapping("/api/items") public class CRUDController { @GetMapping("/{id}") public Item getItem(@PathVariable Long id) { /* Get item logic */ } @PostMapping public Item createItem(@RequestBody Item item) { /* Create item logic */ } // Other CRUD methods... }
Handling request parameters and path variables in Spring Boot RestController:
@RestController
.@RestController @RequestMapping("/api/users") public class ParamController { @GetMapping("/{userId}/orders") public List<Order> getUserOrders(@PathVariable Long userId, @RequestParam(name = "status") String status) { // Logic to fetch user orders based on userId and status } }
Returning JSON responses from a RestController in Spring Boot:
@RestController
.@RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{userId}") public ResponseEntity<User> getUser(@PathVariable Long userId) { User user = userService.getUserById(userId); return ResponseEntity.ok(user); } }
Adding custom headers and status codes in Spring Boot RestController:
@RestController
.@RestController @RequestMapping("/api/products") public class HeaderController { @GetMapping("/{productId}") public ResponseEntity<Product> getProduct(@PathVariable Long productId) { Product product = productService.getProductById(productId); HttpHeaders headers = new HttpHeaders(); headers.add("Custom-Header", "Header-Value"); return new ResponseEntity<>(product, headers, HttpStatus.OK); } }
Using @RequestMapping and @GetMapping annotations in Spring Boot:
@RequestMapping
and @GetMapping
annotations to define URL mappings in a Spring Boot @RestController
.@RestController @RequestMapping("/api") public class RequestMappingController { @GetMapping("/greet") public String greet() { return "Greetings!"; } }
Handling exceptions and errors in a Spring Boot RestController:
@RestController
.@RestControllerAdvice public class ExceptionController { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); } }
Securing RestController endpoints in Spring Boot:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // Security configurations }
Testing strategies for a Spring Boot RestController:
@RestController
.@RunWith(SpringRunner.class) @SpringBootTest public class UserControllerTest { // Unit test methods }
Documenting a RESTful API with Swagger or Springfox in Spring Boot:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
@Configuration @EnableSwagger2 public class SwaggerConfig { // Swagger configurations }
Configuring cross-origin resource sharing (CORS) in Spring Boot:
@RestController
.@Configuration public class CorsConfig implements WebMvcConfigurer { // CORS configurations }
Implementing request validation and data binding in Spring Boot RestController:
@RestController
.@RestController @RequestMapping("/api/orders") public class ValidationController { @PostMapping public ResponseEntity<Order> createOrder(@Valid @RequestBody Order order) { // Logic to create order } }