What a Service Is
A service is a class that holds the work of the app. The controller takes the request, and the service does the work.
A service holds the task list
The field holds three tasks. The list lives in memory.
@Service
public 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));
}A method returns the tasks
The controller calls this method. The method returns the list.
public List<Task> allTasks() {
return tasks;
}Example
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class TaskService {
record Task(String title, boolean done) {
}
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;
}
public static void main(String[] args) {
System.out.println(new TaskService().allTasks());
}
}Key points
- @Service marks a class as a service.
- A service holds the task list in memory.
- Memory means the list lives only while the app runs.
- The controller asks the service for the tasks.
- The service answers with the list.
- One service can serve more than one route.
In this example, the Task record holds a title and a done flag. The @Service marker names the class as a service. The field holds three tasks in memory. The allTasks method returns the list. The main method makes a service and prints its tasks.
Note
A service holds work, not web addresses.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a service hold?