I learned most of these the hard way while building a hotel room booking system with Spring Boot: a REST API for admins and guests to manage rooms, bookings, and availability. The first version worked. The second version, rebuilt with the practices below, was something I would actually show to another developer.
Separate your layers
The single biggest upgrade you can make to a Spring Boot project is also the simplest: stop putting business logic in controllers. Controllers should translate HTTP into method calls and method results back into HTTP. Nothing more. The classic three layers are controller, service, and repository, and each one should have exactly one job:
- Controller: reads the request, calls the service, returns the response.
- Service: holds the business rules, like "a room cannot be double-booked".
- Repository: talks to the database, ideally through Spring Data JPA interfaces.
When I moved booking validation out of my controller and into a BookingService, the controller shrank from 80 lines to 20, and suddenly I could test the rules without spinning up HTTP at all.
Validate at the door
Never trust the request body. Jakarta validation annotations let you declare the rules right on your DTO, and Spring enforces them before your code even runs. Here is a booking request object from my project:
public class BookingRequest {
@NotNull(message = "Room id is required")
private Long roomId;
@NotNull(message = "Check-in date is required")
@FutureOrPresent(message = "Check-in cannot be in the past")
private LocalDate checkIn;
@NotNull(message = "Check-out date is required")
@Future(message = "Check-out must be in the future")
private LocalDate checkOut;
@Email(message = "Guest email must be valid")
@NotBlank(message = "Guest email is required")
private String guestEmail;
// getters and setters
}
Pair it with @Valid on the controller parameter and invalid requests are rejected automatically with a 400 status. Writing this once beats writing null checks in every endpoint forever.
One place for errors
Scattered try-catch blocks produce inconsistent APIs: one endpoint returns a stack trace, another returns an empty 500. A single @RestControllerAdvice class fixes this for the whole application:
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidation(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
return ResponseEntity.badRequest().body(errors);
}
@ExceptionHandler(RoomNotAvailableException.class)
public ResponseEntity<Map<String, String>> handleConflict(
RoomNotAvailableException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", ex.getMessage()));
}
}
Now every validation failure returns a clean field-to-message map, and domain problems like double bookings return a 409 Conflict with a human message. Your frontend developers will thank you.
Keep secrets out of code
Database passwords do not belong in application.properties committed to Git. Use environment variables and reference them:
spring.datasource.url=${DB_URL:jdbc:mysql://localhost:3306/hotel}
spring.datasource.username=${DB_USER:root}
spring.datasource.password=${DB_PASSWORD:}
The part after the colon is a local default, so the app still runs on your machine with zero setup while production injects real secrets. Add application-prod.properties to .gitignore discipline and you will never leak a credential in a repo again.
Paginate every list
The endpoint I am most embarrassed about returned every booking in the database in a single response. It worked fine with forty test rows and would have collapsed with forty thousand. Spring Data makes pagination almost free, so there is no excuse:
@GetMapping("/rooms")
public Page<RoomResponse> listRooms(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return roomService.findAll(PageRequest.of(page, size))
.map(RoomResponse::from);
}
The response now carries the items plus metadata like total pages and total elements, which is exactly what a frontend needs to build page controls. Make this the default for every list endpoint from the start. Retrofitting pagination later means changing every client at once.
Test the sad paths
Happy-path tests feel productive and prove almost nothing. The tests that saved my booking system were the sad ones: booking a room that does not exist, checking out before checking in, and two users racing to book the last available room. Write the sad-path test first, watch it fail, then make it pass. Your future self, debugging at midnight, will be grateful.
A checklist before you ship
Before I call any API done, I run through this list: consistent response shapes, validation on every input DTO, a global exception handler, no secrets in the repo, and pagination on every list endpoint (returning 10,000 rooms in one response is a rite of passage nobody needs twice). It takes an hour and it is the difference between a demo and a product.