Spring Boot Basic Hands-on Exercises
Exercise 1: Build a RESTful Service with Multiple Endpoints
Objective: Create a RESTful service with multiple endpoints that handle different HTTP methods.
Create a
UserController
Class:Define endpoints for creating, retrieving, updating, and deleting a user.
Use HTTP methods:
GET
,POST
,PUT
,DELETE
.
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/users")
public class UserController {
private Map<Integer, String> userDatabase = new HashMap<>();
@PostMapping
public String createUser(@RequestParam String name) {
int id = userDatabase.size() + 1;
userDatabase.put(id, name);
return "User created with ID: " + id;
}
@GetMapping("/{id}")
public String getUser(@PathVariable int id) {
return userDatabase.getOrDefault(id, "User not found");
}
@PutMapping("/{id}")
public String updateUser(@PathVariable int id, @RequestParam String name) {
if (userDatabase.containsKey(id)) {
userDatabase.put(id, name);
return "User updated: " + name;
} else {
return "User not found";
}
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable int id) {
if (userDatabase.containsKey(id)) {
userDatabase.remove(id);
return "User deleted";
} else {
return "User not found";
}
}
}
Test Each Endpoint:
Use a tool like Postman or curl to test each endpoint.
POST
/users?name=John
to create a user.GET
/users/1
to retrieve a user.PUT
/users/1?name=Jane
to update a user.DELETE
/users/1
to delete a user.
Exercise 2: Configure Application Properties
Objective: Customize your Spring Boot application by modifying the application.properties
file.
Change the Server Port:
Open
src/main/resources/
application.properties
.Set the application to run on port 8081.
properties
server.port=8081
Add a Custom Property:
- Define a custom application property to store a welcome message.
properties
app.welcome-message=Welcome to my Spring Boot application!
Access Custom Property in Your Application:
- Use
@Value
annotation to inject the property value into a controller.
- Use
java
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WelcomeController {
@Value("${app.welcome-message}")
private String welcomeMessage;
@GetMapping("/welcome")
public String welcome() {
return welcomeMessage;
}
}
Test the Custom Endpoint:
- Run your application and access
http://localhost:8081/welcome
to see the custom message.
- Run your application and access
Exercise 3: Integrate Spring Data JPA
Objective: Set up a simple persistence layer using Spring Data JPA and an in-memory H2 database.
Add Dependencies:
- Update your
pom.xml
to include Spring Data JPA and H2 Database dependencies.
- Update your
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Configure H2 Database:
- Add H2 configuration to
application.properties
.
- Add H2 configuration to
properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
Create an Entity and Repository:
- Define a
User
entity and aUserRepository
.
- Define a
java
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
// Getters and setters
}
java
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Long> {
}
Update
UserController
to Use Repository:- Modify the controller to persist users using
UserRepository
.
- Modify the controller to persist users using
java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping
public User createUser(@RequestParam String name) {
User user = new User();
user.setName(name);
return userRepository.save(user);
}
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
// Update and Delete methods using userRepository...
}
Test Persistence:
- Use Postman to create and retrieve users, and verify data persistence in the H2 console at
http://localhost:8081/h2-console
.
- Use Postman to create and retrieve users, and verify data persistence in the H2 console at
These exercises should give you a solid foundation in creating and managing Spring Boot applications.
Subscribe to my newsletter
Read articles from Mohamad Mahmood directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Mohamad Mahmood
Mohamad Mahmood
Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He studies at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).