Files
common-library/README.md

355 lines
11 KiB
Markdown

# KriCommon 설정/기능 정리
## 개요
현재 패키지 구조는 아래 4축으로 정리되어 있습니다.
- `com.kri.common.autoconfigure`: Spring Boot 자동 구성 진입점과 `Properties`
- `com.kri.common.feature`: 서비스에서 직접 import/주입/구현하는 공개 기능
- `com.kri.common.runtime`: 자동 구성에 의해 조립되어 동작하는 내부 실행 구성요소
- `com.kri.common.endpoint`: yml 설정으로 자동 노출되는 공통 엔드포인트
설정 키는 `kri.*`만 사용합니다.
---
## 직접 import해서 사용하는 기능
### 인증/보안
#### `com.kri.common.feature.auth.jwt.JwtService`
```java
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
```
- 사용법: 빈 주입 후 `generateAccessToken`, `generateRefreshToken`, `toAuthentication` 호출
- 설명: JWT 발급, 파싱, `Authentication` 변환을 처리합니다.
#### `com.kri.common.feature.auth.dto.JwtUserClaimsDto`
```java
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
```
- 사용법: builder로 사용자 정보를 생성해 `JwtService`에 전달
- 설명: JWT 클레임 공통 DTO입니다.
#### `com.kri.common.feature.auth.apikey.ApiKeyUserClaimsProvider`
```java
import com.kri.common.feature.auth.apikey.ApiKeyUserClaimsProvider;
```
- 사용법: 서비스에서 구현체를 만들어 Bean 등록
- 설명: API Key를 사용자 클레임으로 매핑하는 공개 확장 포인트입니다.
#### `com.kri.common.feature.web.RequestUserContext`
```java
import com.kri.common.feature.web.RequestUserContext;
```
- 사용법: 컨트롤러 파라미터로 선언
- 설명: 현재 인증 사용자와 클라이언트 IP를 전달받는 요청 컨텍스트입니다.
### 웹/페이징
#### `com.kri.common.feature.web.page.PageRequestDto`
```java
import com.kri.common.feature.web.page.PageRequestDto;
```
- 사용법: 조회 API 요청 DTO로 사용
- 설명: pageIndex, pageSize, sortBy, sortDir를 공통 형식으로 받습니다.
#### `com.kri.common.feature.web.page.Pageables`
```java
import com.kri.common.feature.web.page.Pageables;
```
- 사용법: `Pageables.of(req, EntityOrDto.class)`
- 설명: 정렬 가능 필드를 검증해 `Pageable` 객체를 만듭니다.
#### `com.kri.common.feature.web.page.PageResponseDto`
```java
import com.kri.common.feature.web.page.PageResponseDto;
```
- 사용법: `PageResponseDto.from(page)`
- 설명: Spring Data `Page`를 API 응답용 DTO로 감쌉니다.
### Redis
#### `com.kri.common.feature.redis.RedisQueueHelper`
```java
import com.kri.common.feature.redis.RedisQueueHelper;
```
- 사용법: 자동 구성 빈 주입 후 `enqueue`, `blockingDequeue` 사용
- 설명: Redis List 기반 큐 처리 헬퍼입니다.
### HTTP/JSON/Excel
#### `com.kri.common.feature.http.ExternalApiClient`
```java
import com.kri.common.feature.http.ExternalApiClient;
```
- 사용법: `new ExternalApiClient()` 또는 커스텀 `HttpClient`로 생성
- 설명: 문자열 body 기반의 경량 HTTP 클라이언트입니다.
#### `com.kri.common.feature.http.ExternalApiResponse`
```java
import com.kri.common.feature.http.ExternalApiResponse;
```
- 사용법: `ExternalApiClient` 응답 객체로 사용
- 설명: statusCode, headers, body를 묶어 반환합니다.
#### `com.kri.common.feature.json.JsonUtil`
```java
import com.kri.common.feature.json.JsonUtil;
```
- 사용법: JSON 직렬화/역직렬화/맵 변환 수행
- 설명: Jackson 보조 유틸입니다.
#### `com.kri.common.feature.excel.ExcelMapper`
```java
import com.kri.common.feature.excel.ExcelMapper;
```
- 사용법: DTO 리스트나 Map 리스트를 엑셀로 변환
- 설명: 일반 처리와 대용량 스트리밍 읽기/쓰기를 지원합니다.
### 날짜/시간/JPA/Enum/유틸
- `com.kri.common.feature.datetime.*`: 날짜/시간 처리 유틸과 Jackson 어노테이션
- `com.kri.common.feature.jpa.*`: JPA 베이스 엔티티와 enum converter
- `com.kri.common.feature.enums.*`: 코드값 기반 enum 인터페이스와 유틸
- `com.kri.common.feature.cache.*`: 리스트/맵 캐시 베이스 클래스
- `com.kri.common.feature.file.FileUtil`: 파일명/확장자 유틸
- `com.kri.common.feature.util.*`: 문자열, 숫자, UUID 보조 유틸
---
## yml로 설정하는 기능
### 전체 예시
```yaml
kri:
auth:
jwt:
# JWT 서명용 시크릿. 32바이트 이상 권장
secret: "32byte-over-secret-value-required"
# 토큰 발급자 식별자
issuer: "kri-it"
# Access Token 만료 시간(초)
access-token-validity-seconds: 86400
# Refresh Token 만료 시간(초)
refresh-token-validity-seconds: 604800
apikey:
# API Key 인증 기능 활성화
enabled: true
# API Key를 읽을 HTTP 헤더명
header-name: "X-API-Key"
# preload 대상 서비스 코드
service-code: "example-service"
# 서버 시작 시 API Key 캐시 적재 여부
preload-on-startup: true
# 내부 관리용 API 노출 여부
admin-api-enabled: false
admin-allow-ips:
# 내부 관리 API 접근 허용 CIDR
- "127.0.0.1/32"
db:
# API Key 전용 DB 접속 URL
url: "jdbc:mysql://localhost:3306/kri_common"
# API Key 전용 DB 계정
username: "app"
# API Key 전용 DB 비밀번호
password: "secret"
# JDBC 드라이버 클래스
driver-class-name: "com.mysql.cj.jdbc.Driver"
jpa:
# Hibernate SQL 로그 출력 여부
show-sql: false
# Hibernate SQL 포맷팅 여부
format-sql: false
security:
# 기본 Security 자동구성 활성화
enabled: true
public-paths:
# 인증 없이 허용할 공개 경로
- "/v3/api-docs/**"
- "/swagger-ui/**"
swagger:
# Swagger/OpenAPI 자동구성 활성화
enabled: true
# 문서 타이틀
title: "Example API"
# 문서 설명
description: "Example API Docs"
# 문서 버전 표시값
version: "v1"
# Swagger 스캔 대상 base package
base-package: "com.example.api"
allowed-ips:
# Swagger UI / API Docs 접근 허용 IP
- "127.0.0.1"
webmvc:
# 공통 MVC 자동구성 활성화
enabled: true
ip:
additional-cidrs:
# Swagger 접근 허용 CIDR 추가값
- "192.168.0.0/16"
web:
# 공통 웹 예외/trace 필터 활성화
enabled: true
mdc:
# handler/service MDC 기록 활성화
enabled: true
redis:
# Redis 보조 기능 활성화
enabled: true
scheduling:
# @Scheduled 사용을 위한 스케줄링 활성화
enabled: true
error:
expose:
# 에러 응답에 handler 정보 포함 여부
handler: false
# 에러 응답에 service 정보 포함 여부
service: false
```
### 항목별 정리
#### `kri.auth.jwt`
- 대상: JWT 생성/검증
- 사용 대상 클래스: `JwtAutoConfiguration`, `JwtProperties`, `JwtService`
- 설명: issuer, access/refresh 만료 시간, JWT secret을 제어합니다.
#### `kri.auth.apikey`
- 대상: API Key 인증, preload 캐시, 내부 관리용 endpoint
- 사용 대상 클래스: `ApiKeyJpaAutoConfiguration`, `ApiKeyPreloadAutoConfiguration`, `ApiKeyAdminAutoConfiguration`
- 설명: API Key 헤더, preload, admin API 노출, 전용 DB 연결을 제어합니다.
#### `kri.security`
- 대상: 기본 Spring Security 필터체인
- 사용 대상 클래스: `KriSecurityAutoConfiguration`, `KriSecurityProperties`
- 설명: 공개 경로와 JWT/API Key 필터 적용 여부를 제어합니다.
#### `kri.swagger`
- 대상: OpenAPI 문서, Swagger 접근 제어
- 사용 대상 클래스: `KriSwaggerAutoConfiguration`, `KriSwaggerProperties`
- 설명: 문서 메타정보와 스캔 패키지, 허용 IP를 제어합니다.
#### `kri.web`
- 대상: 공통 예외 응답, traceId, MDC
- 사용 대상 클래스: `CommonWebAutoConfiguration`
- 설명: `ErrorAdvice`, `TraceFilter`, MDC 관련 구성을 켜고 끕니다.
#### `kri.webmvc`
- 대상: CORS, Swagger IP 인터셉터, `RequestUserContext` 처리
- 사용 대상 클래스: `KriWebMvcAutoConfiguration`, `KriIpAccessProperties`
- 설명: MVC 확장 기능과 CIDR 기반 접근 제어를 등록합니다.
#### `kri.redis`
- 대상: Redis 큐 헬퍼
- 사용 대상 클래스: `CommonRedisAutoConfiguration`
- 설명: Redis 연결 빈이 있을 때 `RedisQueueHelper`를 자동 등록합니다.
#### `kri.scheduling`
- 대상: 스케줄링 활성화
- 사용 대상 클래스: `CommonSchedulingAutoConfiguration`
- 설명: 서비스에서 `@Scheduled`를 사용할 수 있게 합니다.
#### `kri.error.expose.*`
- 대상: 에러 응답의 MDC 부가 정보 노출
- 사용 대상 클래스: `ErrorAdvice`
- 설명: handler, service 정보를 응답에 포함할지 제어합니다.
---
## 자동 구성에 의해 동작하는 내부 런타임 구성요소
아래 패키지는 서비스에서 직접 import해서 쓰기보다는, 자동 구성에 의해 조립되어 동작하는 내부 구현입니다.
- `com.kri.common.runtime.auth.apikey`
- `ApiKeyAuthFilter`
- `PreloadedApiKeyUserClaimsProvider`
- `persistence.entity`
- `persistence.repository`
- `com.kri.common.runtime.security`
- `JwtAuthenticationFilter`
- `com.kri.common.runtime.swagger`
- `SwaggerIpFilter`
- `com.kri.common.runtime.web`
- `ErrorAdvice`
- `TraceFilter`
- `MdcHandlerConfig`
- `ServiceMdcAspect`
- `com.kri.common.runtime.webmvc`
- `CodeEnumConverter`
- `IpAccessControlInterceptor`
- `IpAccessControlService`
- `IpUtil`
- `RequestUserContextArgumentResolver`
---
## 자동 노출 endpoint
#### `com.kri.common.endpoint.auth.apikey.ApiKeyAdminController`
- 노출 조건: `kri.auth.apikey.admin-api-enabled=true` 그리고 `PreloadedApiKeyUserClaimsProvider` 빈 존재
- 경로: `/internal/apikey/reload`, `/internal/apikey/cache`
- 설명: preload 캐시 재적재와 현재 캐시 조회를 위한 내부 관리용 endpoint입니다.
---
## AutoConfiguration 목록
`src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`
- `com.kri.common.autoconfigure.auth.jwt.JwtAutoConfiguration`
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyJpaAutoConfiguration`
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyPreloadAutoConfiguration`
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyAdminAutoConfiguration`
- `com.kri.common.autoconfigure.security.KriSecurityAutoConfiguration`
- `com.kri.common.autoconfigure.web.CommonWebAutoConfiguration`
- `com.kri.common.autoconfigure.webmvc.KriWebMvcAutoConfiguration`
- `com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration`
- `com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration`
- `com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration`
---
## 검토 메모
- `ApiKeyProperties`의 DB 기본값, `JwtProperties`의 secret 기본값은 의도적으로 유지 중입니다.
- 문서 기준 패키지명은 현재 리팩터링 결과인 `autoconfigure / feature / runtime / endpoint`를 따릅니다.
- 컴파일 검증은 `.\gradlew.bat compileJava` 기준으로 통과했습니다.