Spring boot #211389
Replies: 3 comments
|
What made it click for me was giving each layer one clear job and checking every class against that, instead of following a diagram: Controller = HTTP only. Map the URL, validate input ( Service = the use cases. "Place order", "cancel subscription". This is where the rules live, and where Repository = data access. Usually just a Spring Data interface ( A few habits that prevent most of the mess without overengineering:
@RestController
@RequestMapping("/orders")
class OrderController {
private final OrderService orders;
OrderController(OrderService orders) { this.orders = orders; }
@PostMapping
ResponseEntity<OrderResponse> create(@Valid @RequestBody CreateOrderRequest req) {
OrderResponse created = orders.create(req);
return ResponseEntity.created(URI.create("/orders/" + created.id())).body(created);
}
}
@Service
class OrderService {
private final OrderRepository repo;
OrderService(OrderRepository repo) { this.repo = repo; }
@Transactional
OrderResponse create(CreateOrderRequest req) {
Order order = repo.save(new Order(req.customerId(), req.items()));
return new OrderResponse(order.getId(), order.getStatus().name());
}
}Good references: the official Building REST services with Spring tutorial walks through exactly this structure step by step, and if the project grows, Spring Modulith builds on the package-by-feature idea and verifies the boundaries between features for you. |
|
What helped me was thinking of it like a restaurant:
Example:
If you ever see an To avoid overengineering:
Build it small first. You'll feel when something is in the wrong place, and moving it later is easy. |
here’s what helped me as a beginner,Controller: only handles HTTP (receive the request, call the service, return a response). No business logic. if you’re writing a business rule if inside a controller, move it to the service. To avoid overengineering, skip things like UserService + UserServiceImpl until you actually need two implementations, and use DTOs instead of returning entities directly. Start simple and refactor only when it starts to hurt. Building a small CRUD project (like a to-do API) end to end made me understand it. Good luck! |
Uh oh!
There was an error while loading. Please reload this page.
🏷️ Discussion Type
Question
Body
I'm learning Spring Boot while building a project with a REST API. I'm trying to understand how to keep controllers, services, and repositories well organized without overengineering things. What helped you understand this architecture in practice?
Guidelines
All reactions