Sobes.tech
Senior

How to implement business logic validation in Spring (e.g., age >16, no blocked accounts, card limit not exceeded)?

sobes.tech AI

Answer from AI

In Spring, there are several approaches to validate business logic:

  1. Custom annotations and validators using Bean Validation (JSR-380). For example, you can create an annotation @AgeValid and implement age verification logic.

  2. Service layer — check business rules in services before performing operations. For example, in a service method, verify that age > 16, no blocked accounts exist, and the card limit is not exceeded.

  3. Using AOP (Aspect-Oriented Programming) to separate cross-cutting concerns.

Example of validation in a service:

public void createUser(UserDto userDto) {
    if (userDto.getAge() <= 16) {
        throw new BusinessException("Age must be greater than 16");
    }
    if (accountRepository.existsBlockedAccounts(userDto.getUserId())) {
        throw new BusinessException("User has blocked accounts");
    }
    if (cardRepository.countByUserId(userDto.getUserId()) >= MAX_CARDS_LIMIT) {
        throw new BusinessException("Card limit exceeded");
    }
    // further user creation logic
}

This approach allows centralized control of business rules and easy maintenance.