Spring Boot Basic Hands-on Exercises

Mohamad MahmoodMohamad Mahmood
3 min read

Exercise 1: Build a RESTful Service with Multiple Endpoints

Objective: Create a RESTful service with multiple endpoints that handle different HTTP methods.

  1. 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";
        }
    }
}
  1. 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.

  1. Change the Server Port:

properties

    server.port=8081
  1. Add a Custom Property:

    • Define a custom application property to store a welcome message.

properties

    app.welcome-message=Welcome to my Spring Boot application!
  1. Access Custom Property in Your Application:

    • Use @Value annotation to inject the property value into a controller.

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;
        }
    }
  1. Test the Custom Endpoint:


Exercise 3: Integrate Spring Data JPA

Objective: Set up a simple persistence layer using Spring Data JPA and an in-memory H2 database.

  1. Add Dependencies:

    • Update your pom.xml to include Spring Data JPA and H2 Database dependencies.

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>
  1. Configure H2 Database:

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
  1. Create an Entity and Repository:

    • Define a User entity and a UserRepository.

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> {
    }
  1. Update UserController to Use Repository:

    • Modify the controller to persist users using UserRepository.

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...
    }
  1. Test Persistence:


These exercises should give you a solid foundation in creating and managing Spring Boot applications.

0
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).