Controller, Service, Repository
Three layers.
Real Spring apps are built in three layers. Each layer has one job, and only talks to the layer below it.
- Three layers
- One job each
- Talk downwards
The three layers
The controller handles HTTP. It reads requests, and sends responses. The service holds the business rules, and the transactions. The repository talks to the database. And the database stores the data.
- Controller: HTTP
- Service: rules + transactions
- Repository: data access
- Database
What goes where
Request DTOs, and status codes, belong in the controller. Validation of business rules, and at Transactional, belong in the service. Queries belong in the repository. And entities never leave the service. The controller only sees DTOs.
| Layer | Contains |
|---|---|
| Controller | URLs, DTOs in/out, status codes |
| Service | business rules, @Transactional |
| Repository | queries |
| Entities | stay below the service |
BookService.java
The service is transactional, for every method. All is read only, and maps entities to responses. Create turns a request, into a new entity, saves it, and returns a response.
@Service
@Transactional
public class BookService {
private final BookRepository books;
public BookService(BookRepository books) { this.books = books; }
@Transactional(readOnly = true)
public List<BookResponse> all() {
return books.findAll().stream().map(BookResponse::from).toList();
}
public BookResponse create(CreateBook req) {
Book saved = books.save(new Book(req.title(), req.author(), req.price()));
return BookResponse.from(saved);
}
}A thin controller
The controller only deals with HTTP. Get lists books. Post validates the request, answers two oh one, and lets the service do the work. Run it. Neuromancer is created, with id nine. And it's now the last book in the list.
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService service;
public BookController(BookService service) { this.service = service; }
@GetMapping
public List<BookResponse> all() { return service.all(); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public BookResponse create(@Valid @RequestBody CreateBook req) {
return service.create(req);
}
}$ curl -i --json '{"title":"Neuromancer","author":"William Gibson","price":9.5}'
localhost:8080/books
HTTP/1.1 201
Content-Type: application/json
{"id":9,"title":"Neuromancer","author":"William Gibson","price":9.5}
$ curl -s localhost:8080/books | grep -o '"title":"[^"]*"' | tail -3
"title":"Emma"
"title":"Persuasion"
"title":"Neuromancer"Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
protected Book() {}
public Book(String title, String author, double price) {
this.title = title; this.author = author; this.price = price;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public void setTitle(String title) { this.title = title; }
public void setAuthor(String author) { this.author = author; }
public void setPrice(double price) { this.price = price; }
}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {}Also uses CreateBook.java
public record CreateBook(
@NotBlank String title,
@NotBlank String author,
@Positive double price
) {}Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {
static BookResponse from(Book b) {
return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
}
}Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}Also uses GlobalErrors.java
@RestControllerAdvice
public class GlobalErrors {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail notFound(BookNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
}Also uses data.sql
INSERT INTO book (title, author, price) VALUES
('Dune', 'Frank Herbert', 9.99),
('The Hobbit', 'J.R.R. Tolkien', 8.99),
('Circe', 'Madeline Miller', 10.99),
('Children of Dune', 'Frank Herbert', 8.49),
('Song of Achilles', 'Madeline Miller', 9.49),
('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
('Emma', 'Jane Austen', 6.99),
('Persuasion', 'Jane Austen', 7.49);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueAlso uses BookService.java
@Service
@Transactional
public class BookService {
private final BookRepository books;
public BookService(BookRepository books) { this.books = books; }
@Transactional(readOnly = true)
public List<BookResponse> all() {
return books.findAll().stream().map(BookResponse::from).toList();
}
public BookResponse create(CreateBook req) {
Book saved = books.save(new Book(req.title(), req.author(), req.price()));
return BookResponse.from(saved);
}
}Also uses _curl.sh
curl -i --json '{"title":"Neuromancer","author":"William Gibson","price":9.5}' localhost:8080/books
curl -s localhost:8080/books | grep -o '"title":"[^"]*"' | tail -3Summary
Controllers handle HTTP, services hold rules and transactions, and repositories talk to the database. Next, mapping entities to DTOs.
Key takeaways- Controller
- Service
- Repository