Veritas vos liberabit. Simple and easy validation utility using annotations from jakarta.validation
Find a file
2026-07-17 15:24:52 +09:00
.idea Update Veritas project: add example module, integrate example applications, adjust build configurations, update dependencies, and refine validation result handling. 2026-07-17 12:01:52 +09:00
build-logic Add Jakarta Validation annotations, custom validators, and build configuration setup for the Veritas module. 2026-07-16 02:06:47 +09:00
example Refactor Veritas core: Enhance validation engine, improve MetadataCache concurrency, add message extraction via MessageResolver, introduce custom validator registration, and update tests and documentation. 2026-07-17 15:24:52 +09:00
gradle Update Veritas project: add example module, integrate example applications, adjust build configurations, update dependencies, and refine validation result handling. 2026-07-17 12:01:52 +09:00
validation Refactor Veritas core: Enhance validation engine, improve MetadataCache concurrency, add message extraction via MessageResolver, introduce custom validator registration, and update tests and documentation. 2026-07-17 15:24:52 +09:00
.gitattributes Add Jakarta Validation annotations, custom validators, and build configuration setup for the Veritas module. 2026-07-16 02:06:47 +09:00
.gitignore Add Jakarta Validation annotations, custom validators, and build configuration setup for the Veritas module. 2026-07-16 02:06:47 +09:00
ANNOTATION.md Refactor Veritas core: Enhance validation engine, improve MetadataCache concurrency, add message extraction via MessageResolver, introduce custom validator registration, and update tests and documentation. 2026-07-17 15:24:52 +09:00
gradle.properties Add Jakarta Validation annotations, custom validators, and build configuration setup for the Veritas module. 2026-07-16 02:06:47 +09:00
gradlew Add Jakarta Validation annotations, custom validators, and build configuration setup for the Veritas module. 2026-07-16 02:06:47 +09:00
gradlew.bat Add Jakarta Validation annotations, custom validators, and build configuration setup for the Veritas module. 2026-07-16 02:06:47 +09:00
LICENSE Update Veritas project: add example module, integrate example applications, adjust build configurations, update dependencies, and refine validation result handling. 2026-07-17 12:01:52 +09:00
README.md Refactor Veritas core: Enhance validation engine, improve MetadataCache concurrency, add message extraction via MessageResolver, introduce custom validator registration, and update tests and documentation. 2026-07-17 15:24:52 +09:00
settings.gradle.kts Update Veritas project: add example module, integrate example applications, adjust build configurations, update dependencies, and refine validation result handling. 2026-07-17 12:01:52 +09:00
veritas.png Refactor Veritas core: Enhance validation engine, improve MetadataCache concurrency, add message extraction via MessageResolver, introduce custom validator registration, and update tests and documentation. 2026-07-17 15:24:52 +09:00

VERITAS

"VERITAS VOS LIBERABIT"

Java Version License

VERITAS

Veritas는 기존 Hibernate Validator의 무거운 런타임 의존성과 리플렉션 오버헤드를 탈피하기 위해 설계된 Java 21+ 기반의 레코드 및 클래스 검증 라이브러리입니다.


핵심 특징 (Key Features)

  • Java 21+ 최적화: Java 16+ Record 구조 완벽 지원 및 Java 21의 Pattern Matching을 적극 활용한 현대적이고 직관적인 검증 설계.
  • 초경량 배포 (Zero-Dependency): 타사 로깅 프레임워크나 Spring, Apache Commons 등의 외부 의존성이 전혀 없습니다. 배포본 크기를 수십 KB 단위로 최소화하여 가볍게 탑재 가능합니다.
  • 압도적인 성능 (Reflection Caching): 첫 검증 시점에 클래스 구조를 고속 분석 및 캐싱하는 MetadataCache를 내장하여, 반복 호출 시 리플렉션으로 인한 성능 저하를 차단합니다.
  • 모던 Fluent API: 가독성 높은 빌더 체이닝 흐름 지원.
  • 커스텀 Validator: 기본적으로 내장된 jakarta.validation 어노태이션 이외에 필요한 Validator는 직접 구현(implements ConstrainValidator)하여 추가할 수 있습니다.

시작하기

1. 의존성 추가 (Gradle)

repositories {
    maven {
        name = "Elex Repository"
        url = "https://artifacts.elex-project.com/repository/maven/"
    }
}
dependencies {
    // Veritas Core (Jakarta Validation API 규격 호환)
    implementation("com.elex-project:veritas:1.0.0")
    
    // 표준 명세 어노테이션 사용을 위한 API 의존성
    implementation("jakarta.validation:jakarta.validation-api:4.0.0-M1")
}

2. 검증 대상 정의 (Java Record 또는 Class)

Java 21 Record를 사용해 데이터 전송 객체(DTO)를 선언하고 검증 제약 조건을 추가합니다.

package com.elex_project.veritas.sample;

import jakarta.validation.constraints.*;
import java.math.BigDecimal;

public record RegisterUserDto(
    @NotBlank(message = "사용자 이름은 필수입니다.") 
    String username,

    @Email(message = "이메일 형식이 올바르지 않습니다.") 
    String email,

    @Min(value = 19, message = "만 19세 이상만 가입할 수 있습니다.") 
    int age,

    @DecimalMin(value = "0.0", inclusive = false, message = "포인트는 0 초과여야 합니다.") 
    BigDecimal initialPoint
) {}

3. 검증 실행 패턴

Veritas는 개발자의 코드 스타일에 맞춰 다양한 방식의 진입점을 제공합니다.

패턴 A: 단순 검증 결과 반환

RegisterUserDto dto = new RegisterUserDto(" ", "invalid-email", 15, new BigDecimal("-10"));

ValidationResult result = Veritas.validate(dto);

if (result.isInvalid()) {
    result.violations().forEach(violation -> {
        System.out.println(...);
    });
}

패턴 B: 단정 검증 (실패 시 예외 즉각 투척)

// 검증 실패 시 곧바로 ValidationFailException(RuntimeException)이 발생합니다.
Veritas.validateOrThrow(dto);

패턴 C: Fluent API 체이닝 스타일

Veritas.validate(dto)
       .ifValid(() -> userRepository.save(dto))
       .orElseThrow();


지원하는 제약 조건 어노테이션

Veritas는 아래의 jakarta.validation.constraints 표준 사양을 완벽히 구현 및 지원합니다.

  • 존재 검증: @NotNull, @NotEmpty, @NotBlank, @Null
  • 참/거짓 검증: @AssertTrue, @AssertFalse
  • 범위 & 포맷 검증: @Size, @Pattern, @Email
  • 수치 & 정밀도 검증: @Min, @Max, @DecimalMin, @DecimalMax, @Digits
  • 부호 검증: @Positive, @PositiveOrZero, @Negative, @NegativeOrZero
  • 시간 검증: @Past, @PastOrPresent, @Future, @FutureOrPresent
  • 객체 그래프: @Valid

참고: @NotNull, @NotEmpty, @NotBlank를 제외한 모든 어노테이션들은 검증 대상 값이 null일 경우 기본적으로 검증을 성공(true)처리합니다. 필수 여부는 전적으로 @NotNull 계열 어노테이션에 위임합니다. 다른 검증 조건들과 마찬가지로 @Valid 역시 하위 객체 필드값이 null일 경우에는 검증 오류를 발생시키지 않고 통과시킵니다. 따라서 중첩 객체가 비어있지 않은 필수 입력값이어야 한다면 반드시 @NotNull@Valid를 함께 붙여주어야 합니다.

어노태이션에 관한 자세한 사항은 ANNOTATION.md 문서를 참고하세요.


패키지 아키텍처

내부 구조는 다음과 같이 책임이 명확히 격리되어 있어 확장 및 유지보수가 용이합니다.

com.elex_project.veritas/
├── Veritas.java                  # 통합 Facade 진입점
├── core/
│   ├── ValidationEngine.java     # 검증 루프 엔진
│   └── MetadataCache.java        # 동시성 보장 리플렉션 캐시
│   ├── ConstraintValidator.java  # 검증기 표준 인터페이스
│   ├── MessageResolver.java      # 검증 실패 메시지 제공 인터페이스
│   └── impl/                     # 22종 어노테이션 개별 유효성 검증기 구현체들
├── internal/                     # 내부 사용 유틸리티
├── result/
│   ├── ValidationResult.java     # 검증 성공 여부 및 결과 레코드
│   └── ConstraintViolation.java  # 단일 에러 디테일 정보 레코드
└── exception/
    └── ValidationFailException.java    # 검증 실패 예외 발생 시스템


라이선스 (License)

본 프로젝트는 Apache License 2.0 라이선스 하에 배포 및 관리됩니다.


Copyright © 2026 Elex Project. All rights reserved.

https://www.elex-project.com