Skip to main content

12.1 Assembling Layered Architecture

To keep complex business logic organized, Spring applications generally follow a Layered Architecture. Maintenance and testability improve when each layer has clear responsibilities.

1. Typical 3-Tier Structure​

  1. Presentation Layer (Controller): The entry point that receives requests and returns responses. It handles data format conversion (JSON/XML) and basic validation.
  2. Service Layer (Business Logic): Where the core application logic resides. It sets transaction boundaries and completes business workflows by combining multiple repositories.
  3. Data Access Layer (Repository): Responsible for communication with systems like databases or file systems. JPA Repositories belong to this layer.

2. Separation of DTO and Entity​

It is best to strictly separate Entities(domain models) from DTOs(data transfer objects).

  • Entity: A core class mapped to a database table, containing business rules. It should not be exposed directly to the outside.
  • DTO (Data Transfer Object): An object designed to transfer data according to API specifications. Used for movement between layers.

3. Dependency Injection Flow​

graph LR
Controller --> Service
Service --> Repository
Repository --> DB
  • Controllers depend on Services.
  • Services depend on Repositories.
  • Using interfaces is encouraged for flexibility.

4. Production Code Example​

@Service
@Transactional
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final MemberRepository memberRepository;

public Long order(Long memberId, String itemName, int count) {
// 1. Retrieve entity
Member member = memberRepository.findById(memberId).get();
// 2. Execute business logic and create order
Order order = Order.createOrder(member, itemName, count);
// 3. Save order
orderRepository.save(order);
return order.getId();
}
}

🎯 Key Points​

  • Manage applications by separating them into Controller - Service - Repository layers.
  • Handle business logic and manage transactions in the Service Layer.
  • Keep Entities for internal database use and DTOs for external communication.