🎓 A1Learner
🔍
0 of 50 lessons completed

Splitting Controller and Service

A service layer is the split between web work and app work. The controller handles the web request, and the service holds the task work.

The controller asks, the service answers

The route calls allTasks. The service holds the list.

@GetMapping("/tasks")
public List<Task> tasks() {
    return taskService.allTasks();
}

A second route reuses the service

The count route calls the same method. No list code is repeated.

@GetMapping("/tasks/count")
public int count() {
    return taskService.allTasks().size();
}

Example

import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    private final TaskService taskService;

    public TaskController(TaskService taskService) {
        this.taskService = taskService;
    }

    @GetMapping("/tasks")
    public List<Task> tasks() {
        return taskService.allTasks();
    }
}

@Service
class TaskService {

    private final List<Task> tasks = List.of(new Task("Buy milk", false), new Task("Ship Spring Boot", true), new Task("Read a book", false));

    public List<Task> allTasks() {
        return tasks;
    }
}

record Task(String title, boolean done) {
}

Key points

  • The controller reads the request and sends the answer.
  • The service holds the task list and the rules for it.
  • The controller calls one service method per job.
  • A service method has a name that states its job.
  • New routes can reuse the same service method.

In this example, the controller holds the service in a final field. The constructor takes the service as a parameter. The route answers GET /tasks. The method calls allTasks on the service. The service holds three tasks in memory. The Task record holds a title and a done flag.

Note

Keep the controller short, and put the work in the service.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the controller do in a service layer split?