260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용

This commit is contained in:
2026-02-12 11:22:05 +09:00
parent bc5af86bcd
commit 88e9845c1c
61 changed files with 3029 additions and 2667 deletions

View File

@@ -20,6 +20,7 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을
- 주요 클래스: `ExternalApiClient`, `ExternalApiResponse` - 주요 클래스: `ExternalApiClient`, `ExternalApiResponse`
지원 메서드(문자열 body 기반) 지원 메서드(문자열 body 기반)
- `ExternalApiResponse get(String url, Map<String,String> headers)` - `ExternalApiResponse get(String url, Map<String,String> headers)`
- `ExternalApiResponse post(String url, Map<String,String> headers, String body)` - `ExternalApiResponse post(String url, Map<String,String> headers, String body)`
- `ExternalApiResponse put(String url, Map<String,String> headers, String body)` - `ExternalApiResponse put(String url, Map<String,String> headers, String body)`
@@ -27,11 +28,13 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을
- `ExternalApiResponse delete(String url, Map<String,String> headers)` - `ExternalApiResponse delete(String url, Map<String,String> headers)`
기본 동작 기본 동작
- 연결 타임아웃: 10초, 요청 타임아웃: 30초 - 연결 타임아웃: 10초, 요청 타임아웃: 30초
- body가 있고 `Content-Type` 헤더가 없으면 자동으로 `application/json; charset=utf-8` 설정 - body가 있고 `Content-Type` 헤더가 없으면 자동으로 `application/json; charset=utf-8` 설정
- 예외 발생 시 `RuntimeException`으로 래핑하여 전달하며, `InterruptedException` 발생 시 인터럽트 플래그를 복원 - 예외 발생 시 `RuntimeException`으로 래핑하여 전달하며, `InterruptedException` 발생 시 인터럽트 플래그를 복원
응답 객체(`ExternalApiResponse`) 응답 객체(`ExternalApiResponse`)
- 필드: `statusCode`(int), `headers`(Map<String, List<String>>), `body`(String) - 필드: `statusCode`(int), `headers`(Map<String, List<String>>), `body`(String)
- 정적 팩토리: `ExternalApiResponse.of(int, HttpHeaders, String)` - 정적 팩토리: `ExternalApiResponse.of(int, HttpHeaders, String)`
@@ -77,6 +80,7 @@ ExternalApiClient client = new ExternalApiClient(httpClient, Duration.ofSeconds(
``` ```
주의사항 주의사항
- 메서드 시그니처는 문자열 기반 body를 사용하므로, JSON 외 포맷을 전송할 경우 적절한 `Content-Type`을 직접 지정하세요. - 메서드 시그니처는 문자열 기반 body를 사용하므로, JSON 외 포맷을 전송할 경우 적절한 `Content-Type`을 직접 지정하세요.
- 대용량 응답이 예상된다면 현재 구현은 `BodyHandlers.ofString()`을 사용한다는 점에 유의하세요. - 대용량 응답이 예상된다면 현재 구현은 `BodyHandlers.ofString()`을 사용한다는 점에 유의하세요.
@@ -264,6 +268,7 @@ kri:
- com.kri.common.scheduling: 스케줄링 자동 활성화 (선택 사용) - com.kri.common.scheduling: 스케줄링 자동 활성화 (선택 사용)
권장 의존 방향(순환 금지): 권장 의존 방향(순환 금지):
- auth.jwt, auth.apikey → 다른 모듈에 의존하지 않음(핵심 도메인 유틸) - auth.jwt, auth.apikey → 다른 모듈에 의존하지 않음(핵심 도메인 유틸)
- security → auth.* 에 의존(필터 순서/체인 구성) - security → auth.* 에 의존(필터 순서/체인 구성)
- web, webmvc → spring-web 중심, security에 의존하지 않음 - web, webmvc → spring-web 중심, security에 의존하지 않음
@@ -272,25 +277,33 @@ kri:
### 0.2 AutoConfiguration 로딩과 오버라이드 전략 ### 0.2 AutoConfiguration 로딩과 오버라이드 전략
자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음 순서/특징을 가집니다. 자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음
순서/특징을 가집니다.
1) com.kri.common.auth.jwt.JwtAutoConfiguration 1) com.kri.common.auth.jwt.JwtAutoConfiguration
- JwtProperties 바인딩, JwtService, ApiKeyAuthFilter 등 기초 컴포넌트 제공 - JwtProperties 바인딩, JwtService, ApiKeyAuthFilter 등 기초 컴포넌트 제공
2) com.kri.common.security.KriSecurityAutoConfiguration 2) com.kri.common.security.KriSecurityAutoConfiguration
- SecurityFilterChain 기본 구성, @EnableMethodSecurity 활성화, 필터 체인에 ApiKey → JWT 순서로 필터 삽입 - SecurityFilterChain 기본 구성, @EnableMethodSecurity 활성화, 필터 체인에 ApiKey → JWT 순서로 필터 삽입
- before = SecurityAutoConfiguration 으로 Spring 기본 보안 자동구성보다 먼저 개입 - before = SecurityAutoConfiguration 으로 Spring 기본 보안 자동구성보다 먼저 개입
3) com.kri.common.web.CommonWebAutoConfiguration, com.kri.common.webmvc.KriWebMvcAutoConfiguration 3) com.kri.common.web.CommonWebAutoConfiguration, com.kri.common.webmvc.KriWebMvcAutoConfiguration
- 공통 예외/로깅, CORS, Swagger 접근 IP 제어 인터셉터 - 공통 예외/로깅, CORS, Swagger 접근 IP 제어 인터셉터
4) com.kri.common.swagger.KriSwaggerAutoConfiguration 4) com.kri.common.swagger.KriSwaggerAutoConfiguration
- OpenAPI/Swagger 설정, Bearer/JWT + API Key SecurityScheme 등록 - OpenAPI/Swagger 설정, Bearer/JWT + API Key SecurityScheme 등록
5) com.kri.common.redis.CommonRedisAutoConfiguration, com.kri.common.scheduling.CommonSchedulingAutoConfiguration 5) com.kri.common.redis.CommonRedisAutoConfiguration,
com.kri.common.scheduling.CommonSchedulingAutoConfiguration
- 선택 기능: RedisQueueHelper, @EnableScheduling - 선택 기능: RedisQueueHelper, @EnableScheduling
오버라이드 규칙: 오버라이드 규칙:
- 동일 타입의 Bean을 서비스에서 정의하면 @ConditionalOnMissingBean에 의해 서비스 정의가 우선 - 동일 타입의 Bean을 서비스에서 정의하면 @ConditionalOnMissingBean에 의해 서비스 정의가 우선
- 프로퍼티로 on/off 토글(@ConditionalOnProperty) - 프로퍼티로 on/off 토글(@ConditionalOnProperty)
@@ -389,7 +402,7 @@ KriCommon은 다음 AutoConfiguration 들을 제공합니다.
모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다. 모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다.
| 클래스 | 역할 요약 | | 클래스 | 역할 요약 |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------- | |---------------------------------------------------------------|---------------------------------------------------------------------------------------|
| `com.kri.common.auth.jwt.JwtAutoConfiguration` | `JwtProperties`, `ApiKeyProperties` 바인딩 + `JwtService`, `ApiKeyAuthFilter` 자동 Bean 생성 | | `com.kri.common.auth.jwt.JwtAutoConfiguration` | `JwtProperties`, `ApiKeyProperties` 바인딩 + `JwtService`, `ApiKeyAuthFilter` 자동 Bean 생성 |
| `com.kri.common.security.KriSecurityAutoConfiguration` | SecurityFilterChain 기본 구성(JWT + API Key 필터) + `@EnableMethodSecurity` | | `com.kri.common.security.KriSecurityAutoConfiguration` | SecurityFilterChain 기본 구성(JWT + API Key 필터) + `@EnableMethodSecurity` |
| `com.kri.common.web.CommonWebAutoConfiguration` | 공통 예외 처리(`ErrorAdvice`), `TraceFilter` 등록 | | `com.kri.common.web.CommonWebAutoConfiguration` | 공통 예외 처리(`ErrorAdvice`), `TraceFilter` 등록 |
@@ -499,7 +512,7 @@ public class JwtProperties {
**프로퍼티 요약** **프로퍼티 요약**
| 프로퍼티 | 타입 | 기본값 | 설명 | | 프로퍼티 | 타입 | 기본값 | 설명 |
| --------------------------------------------- | ------ | ------------ | -------------------------------------- | |-----------------------------------------------|--------|--------------|----------------------------------------|
| `kri.auth.jwt.secret` | String | (기본값 있음) | HMAC 서명용 시크릿(최소 32자 이상, 서비스별로 꼭 변경 추천) | | `kri.auth.jwt.secret` | String | (기본값 있음) | HMAC 서명용 시크릿(최소 32자 이상, 서비스별로 꼭 변경 추천) |
| `kri.auth.jwt.issuer` | String | `kri-it` | 토큰 발급자 | | `kri.auth.jwt.issuer` | String | `kri-it` | 토큰 발급자 |
| `kri.auth.jwt.access-token-validity-seconds` | long | 86,400 (24h) | Access Token 만료(초) | | `kri.auth.jwt.access-token-validity-seconds` | long | 86,400 (24h) | Access Token 만료(초) |
@@ -600,7 +613,7 @@ public class ApiKeyProperties {
**프로퍼티 요약** **프로퍼티 요약**
| 프로퍼티 | 타입 | 기본값 | 설명 | | 프로퍼티 | 타입 | 기본값 | 설명 |
| ----------------------------- | ------- | ----------- | ----------------------- | |-------------------------------|---------|-------------|-------------------------|
| `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 사용 여부 | | `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 사용 여부 |
| `kri.auth.apikey.header-name` | String | `X-API-Key` | API Key 를 읽을 HTTP 헤더 이름 | | `kri.auth.apikey.header-name` | String | `X-API-Key` | API Key 를 읽을 HTTP 헤더 이름 |
@@ -677,7 +690,7 @@ public class KriSecurityProperties {
**프로퍼티 요약** **프로퍼티 요약**
| 프로퍼티 | 타입 | 기본값 (일부) | 설명 | | 프로퍼티 | 타입 | 기본값 (일부) | 설명 |
| --------------------------- | ------------ | ---------------- | -------------------------- | |-----------------------------|--------------|------------------|----------------------------|
| `kri.security.enabled` | boolean | `true` | 공통 Security 자동 구성 사용 여부 | | `kri.security.enabled` | boolean | `true` | 공통 Security 자동 구성 사용 여부 |
| `kri.security.public-paths` | List<String> | Swagger 관련 패턴 포함 | `permitAll()` 로 열어둘 URL 목록 | | `kri.security.public-paths` | List<String> | Swagger 관련 패턴 포함 | `permitAll()` 로 열어둘 URL 목록 |
@@ -866,7 +879,7 @@ public class KriIpAccessProperties {
**프로퍼티 요약** **프로퍼티 요약**
| 프로퍼티 | 타입 | 설명 | | 프로퍼티 | 타입 | 설명 |
| -------------------------------- | ------------ | --------------------------------- | |----------------------------------|--------------|-----------------------------------|
| `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off | | `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off |
| `kri.webmvc.ip.additional-cidrs` | List<String> | 기본 CIDR 목록에 *추가*할 CIDR 리스트 | | `kri.webmvc.ip.additional-cidrs` | List<String> | 기본 CIDR 목록에 *추가*할 CIDR 리스트 |
@@ -944,7 +957,7 @@ public class CommonRedisAutoConfiguration {
**프로퍼티** **프로퍼티**
| 프로퍼티 | 타입 | 기본값 | 설명 | | 프로퍼티 | 타입 | 기본값 | 설명 |
| ---------------------- | ------- | ----- | ---------------------- | |------------------------|---------|-------|------------------------|
| `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 | | `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 |
#### 4.6.2. RedisQueueHelper 사용 예시 #### 4.6.2. RedisQueueHelper 사용 예시
@@ -980,7 +993,7 @@ public class CommonSchedulingAutoConfiguration { }
**프로퍼티** **프로퍼티**
| 프로퍼티 | 타입 | 기본값 | 설명 | | 프로퍼티 | 타입 | 기본값 | 설명 |
| --------------------------- | ------- | ----- | -------------------------- | |-----------------------------|---------|-------|----------------------------|
| `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 | | `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 |
서비스 쪽에서는 단순히: 서비스 쪽에서는 단순히:
@@ -1022,7 +1035,6 @@ common:
**던지기만 하면** `ErrorAdvice`가 잡아서 `ProblemDetail` 포맷으로 응답을 내려줍니다. **던지기만 하면** `ErrorAdvice`가 잡아서 `ProblemDetail` 포맷으로 응답을 내려줍니다.
#### 4.9.2. 기본 사용 패턴 #### 4.9.2. 기본 사용 패턴
* 4.9.2.1. Not Found (404) * 4.9.2.1. Not Found (404)
@@ -1040,12 +1052,14 @@ public User getUserOrThrow(String userId) {
); );
} }
``` ```
- HTTP 상태: 404 - HTTP 상태: 404
- code: "USER_NOT_FOUND" - code: "USER_NOT_FOUND"
- message: "해당 사용자를 찾을 수 없습니다." - message: "해당 사용자를 찾을 수 없습니다."
- extras: { "userId": "..." } - extras: { "userId": "..." }
* 4.9.2.2. Conflict (409) * 4.9.2.2. Conflict (409)
``` ```
if (userRepository.existsByLoginId(loginId)) { if (userRepository.existsByLoginId(loginId)) {
throw BusinessException.conflict( throw BusinessException.conflict(
@@ -1056,6 +1070,7 @@ if (userRepository.existsByLoginId(loginId)) {
``` ```
* 4.9.2.3. Forbidden (403) * 4.9.2.3. Forbidden (403)
``` ```
if (!currentUser.canAccess(targetProject)) { if (!currentUser.canAccess(targetProject)) {
throw BusinessException.forbidden( throw BusinessException.forbidden(
@@ -1066,7 +1081,9 @@ if (!currentUser.canAccess(targetProject)) {
``` ```
#### 4.9.3. 임의 상태 코드 지정: of(...) #### 4.9.3. 임의 상태 코드 지정: of(...)
of(HttpStatus status, String code, String message) 팩토리로 원하는 상태 코드를 직접 지정할 수 있습니다. of(HttpStatus status, String code, String message) 팩토리로 원하는 상태 코드를 직접 지정할 수 있습니다.
``` ```
throw BusinessException.of( throw BusinessException.of(
HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST,
@@ -1075,7 +1092,9 @@ throw BusinessException.of(
).with("param", "startDate"); ).with("param", "startDate");
``` ```
추가 정보를 한 번에 넘기고 싶으면: 추가 정보를 한 번에 넘기고 싶으면:
``` ```
Map<String, Object> extras = Map.of( Map<String, Object> extras = Map.of(
"param", "startDate", "param", "startDate",
@@ -1089,21 +1108,27 @@ throw BusinessException.of(
extras extras
); );
``` ```
> 실제 구현에는 of(status, code, message, Map<String,Object>) 시그니처가 존재합니다. > 실제 구현에는 of(status, code, message, Map<String,Object>) 시그니처가 존재합니다.
#### 4.9.4. extras 체이닝: with(...) 활용 #### 4.9.4. extras 체이닝: with(...) 활용
with(key, value)는 새로운 예외 인스턴스를 리턴하는 체이닝 메서드입니다. with(key, value)는 새로운 예외 인스턴스를 리턴하는 체이닝 메서드입니다.
``` ```
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.") throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
.with("userId", userId) .with("userId", userId)
.with("searchType", "INTRANET"); .with("searchType", "INTRANET");
``` ```
* 내부적으로 extras를 복사해 새 인스턴스를 만드는 방식이라, immutable 스타일로 안전하게 체이닝할 수 있습니다. * 내부적으로 extras를 복사해 새 인스턴스를 만드는 방식이라, immutable 스타일로 안전하게 체이닝할 수 있습니다.
#### 4.9.5. Service / Controller에서의 사용 위치 #### 4.9.5. Service / Controller에서의 사용 위치
Service에서 던지고, Controller는 깔끔하게 유지 Service에서 던지고, Controller는 깔끔하게 유지
Service 예시 Service 예시
``` ```
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -1124,6 +1149,7 @@ public class UserService {
``` ```
Controller 예시 Controller 예시
``` ```
@RestController @RestController
@RequestMapping("/api/users") @RequestMapping("/api/users")
@@ -1145,12 +1171,15 @@ public class UserController {
* ErrorAdvice가 @ExceptionHandler(BusinessException.class)로 처리 * ErrorAdvice가 @ExceptionHandler(BusinessException.class)로 처리
#### 4.9.6. 실제 응답 JSON 예시 #### 4.9.6. 실제 응답 JSON 예시
``` ```
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.") throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
.with("userId", "u-123"); .with("userId", "u-123");
``` ```
요청 URL이 /api/users/u-123인 경우, 응답은 대략 다음과 같은 형태입니다. 요청 URL이 /api/users/u-123인 경우, 응답은 대략 다음과 같은 형태입니다.
```json ```json
{ {
"type": "about:blank", "type": "about:blank",
@@ -1166,6 +1195,7 @@ throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없
"userId": "u-123" "userId": "u-123"
} }
``` ```
> 이 포맷은 ErrorAdvice에서 공통으로 생성합니다. > 이 포맷은 ErrorAdvice에서 공통으로 생성합니다.
#### 4.9.7. 로그 출력 정책 #### 4.9.7. 로그 출력 정책
@@ -1187,6 +1217,7 @@ ErrorAdvice 내부 로깅 정책(요약):
#### 4.9.8. 에러 코드 enum으로 관리하기 (선택) #### 4.9.8. 에러 코드 enum으로 관리하기 (선택)
서비스에서 에러 코드를 enum으로 관리하면 나중에 유지보수가 쉬워집니다. 서비스에서 에러 코드를 enum으로 관리하면 나중에 유지보수가 쉬워집니다.
``` ```
public enum UserErrorCodes { public enum UserErrorCodes {
USER_NOT_FOUND, USER_NOT_FOUND,
@@ -1199,6 +1230,7 @@ throw BusinessException.notFound(
"사용자를 찾을 수 없습니다." "사용자를 찾을 수 없습니다."
).with("userId", userId); ).with("userId", userId);
``` ```
#### 4.9.9. 요약 #### 4.9.9. 요약
1. 던지는 쪽 (Service) 1. 던지는 쪽 (Service)
@@ -1215,6 +1247,7 @@ throw BusinessException.notFound(
* FE에서는 code 기준으로 에러 분기 처리하면 됨 * FE에서는 code 기준으로 에러 분기 처리하면 됨
--- ---
## 5. example-service 적용 요약 ## 5. example-service 적용 요약
1. **의존성 추가** 1. **의존성 추가**
@@ -1273,7 +1306,8 @@ throw BusinessException.notFound(
- Swagger 페이지가 접근 불가(403/404) - Swagger 페이지가 접근 불가(403/404)
- 원인: IP 접근 제어 또는 public-paths 미설정 - 원인: IP 접근 제어 또는 public-paths 미설정
- 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로 포함 - 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로
포함
- ApiKeyUserClaimsProvider가 동작하지 않음 - ApiKeyUserClaimsProvider가 동작하지 않음
- 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false` - 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false`
@@ -1284,13 +1318,16 @@ throw BusinessException.notFound(
## 8. FAQ ## 8. FAQ
- Q. API Key와 JWT는 어떻게 같이 쓰나요? - Q. API Key와 JWT는 어떻게 같이 쓰나요?
- A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를 권장합니다. - A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를
권장합니다.
- Q. ROLE 매핑은 어디서 바꾸나요? - Q. ROLE 매핑은 어디서 바꾸나요?
- A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를 오버라이드하거나 래핑하십시오. - A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를
오버라이드하거나 래핑하십시오.
- Q. 기본 Security를 전면 교체할 수 있나요? - Q. 기본 Security를 전면 교체할 수 있나요?
- A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선 적용됩니다. - A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선
적용됩니다.
--- ---

View File

@@ -10,4 +10,5 @@ import org.springframework.context.annotation.Import;
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true") @ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
@Import(ApiKeyAdminController.class) // ✅ 컴포넌트 스캔 없이도 Bean 등록 @Import(ApiKeyAdminController.class) // ✅ 컴포넌트 스캔 없이도 Bean 등록
public class ApiKeyAdminAutoConfiguration { public class ApiKeyAdminAutoConfiguration {
} }

View File

@@ -2,6 +2,8 @@ package com.kri.common.auth.apikey;
import com.kri.common.auth.dto.JwtUserClaimsDto; import com.kri.common.auth.dto.JwtUserClaimsDto;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.web.util.matcher.IpAddressMatcher; import org.springframework.security.web.util.matcher.IpAddressMatcher;
@@ -11,13 +13,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Map;
@RestController @RestController
@RequestMapping("/internal/apikey") @RequestMapping("/internal/apikey")
@ConditionalOnProperty(prefix="kri.auth.apikey", name="admin-api-enabled", havingValue="true") @ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
public class ApiKeyAdminController { public class ApiKeyAdminController {
private final ApiKeyProperties props; private final ApiKeyProperties props;
private final PreloadedApiKeyUserClaimsProvider provider; private final PreloadedApiKeyUserClaimsProvider provider;
private final List<IpAddressMatcher> allow; private final List<IpAddressMatcher> allow;
@@ -35,7 +35,9 @@ public class ApiKeyAdminController {
return new ReloadResult(count); return new ReloadResult(count);
} }
/** 현재 캐시 상태(키는 마스킹) */ /**
* 현재 캐시 상태(키는 마스킹)
*/
@GetMapping("/cache") @GetMapping("/cache")
public List<CachedKeyView> cache(HttpServletRequest req) { public List<CachedKeyView> cache(HttpServletRequest req) {
assertAllowed(req); assertAllowed(req);
@@ -46,19 +48,32 @@ public class ApiKeyAdminController {
} }
private void assertAllowed(HttpServletRequest req) { private void assertAllowed(HttpServletRequest req) {
if (!props.isAdminApiEnabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND); if (!props.isAdminApiEnabled()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
String remote = req.getRemoteAddr(); String remote = req.getRemoteAddr();
boolean ok = allow.stream().anyMatch(m -> m.matches(remote)); boolean ok = allow.stream().anyMatch(m -> m.matches(remote));
if (!ok) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote); if (!ok) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
}
} }
private String mask(String raw) { private String mask(String raw) {
if (raw == null) return ""; if (raw == null) {
return "";
}
int n = raw.length(); int n = raw.length();
if (n <= 8) return raw.charAt(0) + "****"; if (n <= 8) {
return raw.charAt(0) + "****";
}
return raw.substring(0, 4) + "****" + raw.substring(n - 4); return raw.substring(0, 4) + "****" + raw.substring(n - 4);
} }
public record ReloadResult(int cachedKeyCount) {} public record ReloadResult(int cachedKeyCount) {
public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {}
}
public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {
}
} }

View File

@@ -5,18 +5,16 @@ import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/** /**
* X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터. * X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터. - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임. -
* - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임. * 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
* - 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
*/ */
@RequiredArgsConstructor @RequiredArgsConstructor
public class ApiKeyAuthFilter extends OncePerRequestFilter { public class ApiKeyAuthFilter extends OncePerRequestFilter {

View File

@@ -2,6 +2,9 @@ package com.kri.common.auth.apikey;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration;
@@ -19,10 +22,6 @@ import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/* /*
* @Primary 절대 금지 * @Primary 절대 금지
* 메인 JPA와 완전히 분리 * 메인 JPA와 완전히 분리
@@ -59,9 +58,10 @@ public class ApiKeyJpaAutoConfiguration {
ds.setDriverClassName(db.getDriverClassName()); ds.setDriverClassName(db.getDriverClassName());
return ds; return ds;
} }
/** /**
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식 * ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식 - intranet-extension처럼 HibernateJpaAutoConfiguration을
* - intranet-extension처럼 HibernateJpaAutoConfiguration을 exclude 해도 동작 * exclude 해도 동작
*/ */
@Bean(name = "apiKeyEntityManagerFactory") @Bean(name = "apiKeyEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory( public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory(
@@ -101,9 +101,8 @@ public class ApiKeyJpaAutoConfiguration {
} }
/** /**
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서 * ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서 'jpaMappingContext'가 없을 때만 보완해준다.
* 'jpaMappingContext'가 없을 때만 보완해준다. * <p>
*
* 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다. * 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다.
*/ */
@Bean(name = "jpaMappingContext") @Bean(name = "jpaMappingContext")

View File

@@ -1,11 +1,10 @@
package com.kri.common.auth.apikey; package com.kri.common.auth.apikey;
import java.util.List;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
@Getter @Getter
@Setter @Setter
@ConfigurationProperties(prefix = "kri.auth.apikey") @ConfigurationProperties(prefix = "kri.auth.apikey")
@@ -17,41 +16,60 @@ public class ApiKeyProperties {
private boolean enabled = false; private boolean enabled = false;
/** /**
* API Key 를 읽어올 헤더 이름 * API Key 를 읽어올 헤더 이름 예: X-API-Key, X-EXTERNAL-KEY 등
* 예: X-API-Key, X-EXTERNAL-KEY 등
*/ */
private String headerName = "X-API-Key"; private String headerName = "X-API-Key";
/** 이 서비스의 코드 (서비스별 preload 범위 결정) */ /**
* 이 서비스의 코드 (서비스별 preload 범위 결정)
*/
private String serviceCode; private String serviceCode;
/** 기동 시 preload 할지 */ /**
* 기동 시 preload 할지
*/
private boolean preloadOnStartup = false; private boolean preloadOnStartup = false;
/** 내부 관리 API(리로드/조회) 노출 여부 */ /**
* 내부 관리 API(리로드/조회) 노출 여부
*/
private boolean adminApiEnabled = false; private boolean adminApiEnabled = false;
/** 내부 관리 API 접근 허용 IP(CIDR) */ /**
* 내부 관리 API 접근 허용 IP(CIDR)
*/
private List<String> adminAllowIps = List.of("127.0.0.1/32"); private List<String> adminAllowIps = List.of("127.0.0.1/32");
/** apikey 전용 DB 설정(기본값 포함) */ /**
* apikey 전용 DB 설정(기본값 포함)
*/
private Db db = new Db(); private Db db = new Db();
/** apikey 전용 JPA 옵션 */ /**
* apikey 전용 JPA 옵션
*/
private Jpa jpa = new Jpa(); private Jpa jpa = new Jpa();
@Getter @Setter @Getter
@Setter
public static class Jpa { public static class Jpa {
/** hibernate.show_sql */
/**
* hibernate.show_sql
*/
private boolean showSql = false; private boolean showSql = false;
/** hibernate.format_sql */ /**
* hibernate.format_sql
*/
private boolean formatSql = false; private boolean formatSql = false;
} }
@Getter @Setter @Getter
@Setter
public static class Db { public static class Db {
//내부 통신용 url //내부 통신용 url
private String url = private String url =
"jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8"; "jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8";

View File

@@ -4,8 +4,8 @@ import com.kri.common.auth.dto.JwtUserClaimsDto;
import java.util.Optional; import java.util.Optional;
/** /**
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. * 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면
* 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면 된다. * 된다.
*/ */
public interface ApiKeyUserClaimsProvider { public interface ApiKeyUserClaimsProvider {

View File

@@ -3,23 +3,25 @@ package com.kri.common.auth.apikey;
import com.kri.common.auth.dto.JwtUserClaimsDto; import com.kri.common.auth.dto.JwtUserClaimsDto;
import com.kri.common.auth.persistence.entity.TApiKeyEntity; import com.kri.common.auth.persistence.entity.TApiKeyEntity;
import com.kri.common.auth.persistence.repository.ApiKeyRepository; import com.kri.common.auth.persistence.repository.ApiKeyRepository;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.util.StringUtils;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.util.StringUtils;
public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider, ApplicationRunner { public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider,
ApplicationRunner {
private final ApiKeyProperties props; private final ApiKeyProperties props;
private final ApiKeyRepository repo; private final ApiKeyRepository repo;
/** 캐시를 통째로 교체(swap)하기 위한 AtomicReference */ /**
* 캐시를 통째로 교체(swap)하기 위한 AtomicReference
*/
private final AtomicReference<Map<String, JwtUserClaimsDto>> cacheRef = private final AtomicReference<Map<String, JwtUserClaimsDto>> cacheRef =
new AtomicReference<>(Collections.emptyMap()); new AtomicReference<>(Collections.emptyMap());
@@ -28,22 +30,34 @@ public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvid
this.repo = repo; this.repo = repo;
} }
/** 런타임에는 DB 조회 금지: 캐시만 조회 */ /**
* 런타임에는 DB 조회 금지: 캐시만 조회
*/
@Override @Override
public Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey) { public Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey) {
if (!StringUtils.hasText(apiKey)) return Optional.empty(); if (!StringUtils.hasText(apiKey)) {
return Optional.empty();
}
return Optional.ofNullable(cacheRef.get().get(apiKey)); return Optional.ofNullable(cacheRef.get().get(apiKey));
} }
/** 기동 시 preload */ /**
* 기동 시 preload
*/
@Override @Override
public void run(ApplicationArguments args) { public void run(ApplicationArguments args) {
if (!props.isEnabled()) return; if (!props.isEnabled()) {
if (!props.isPreloadOnStartup()) return; return;
}
if (!props.isPreloadOnStartup()) {
return;
}
reloadFromDb(); reloadFromDb();
} }
/** 운영용: DB에서 다시 읽어 캐시 전체 교체 */ /**
* 운영용: DB에서 다시 읽어 캐시 전체 교체
*/
public synchronized int reloadFromDb() { public synchronized int reloadFromDb() {
if (!StringUtils.hasText(props.getServiceCode())) { if (!StringUtils.hasText(props.getServiceCode())) {
// serviceCode 없으면 preload 불가 → 안전하게 빈 캐시 // serviceCode 없으면 preload 불가 → 안전하게 빈 캐시
@@ -68,7 +82,9 @@ public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvid
return next.size(); return next.size();
} }
/** Admin 조회용(마스킹은 컨트롤러에서) */ /**
* Admin 조회용(마스킹은 컨트롤러에서)
*/
public Map<String, JwtUserClaimsDto> snapshot() { public Map<String, JwtUserClaimsDto> snapshot() {
return cacheRef.get(); return cacheRef.get();
} }

View File

@@ -20,8 +20,8 @@ public class JwtAutoConfiguration {
} }
/** /**
* ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성. * ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성. (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서
* (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서 addFilterBefore 로 수행) * addFilterBefore 로 수행)
*/ */
@Bean @Bean
@ConditionalOnBean(ApiKeyUserClaimsProvider.class) @ConditionalOnBean(ApiKeyUserClaimsProvider.class)

View File

@@ -1,6 +1,9 @@
package com.kri.common.auth.jwt; package com.kri.common.auth.jwt;
import lombok.*; import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter @Getter

View File

@@ -1,23 +1,29 @@
package com.kri.common.auth.jwt; package com.kri.common.auth.jwt;
import com.kri.common.auth.dto.JwtUserClaimsDto; import com.kri.common.auth.dto.JwtUserClaimsDto;
import io.jsonwebtoken.*; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys; import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.*;
/** /**
* 공통 JWT 유틸 서비스 * 공통 JWT 유틸 서비스 - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 - 일반 JWT + 내부 고정 토큰 둘 다 지원
* - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱
* - 일반 JWT + 내부 고정 토큰 둘 다 지원
*/ */
@RequiredArgsConstructor @RequiredArgsConstructor
public class JwtService { public class JwtService {
@@ -31,7 +37,8 @@ public class JwtService {
// 시크릿 검증: HS256 권장 최소 길이(32바이트 이상) // 시크릿 검증: HS256 권장 최소 길이(32바이트 이상)
String secret = properties.getSecret(); String secret = properties.getSecret();
if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) { if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) {
throw new IllegalStateException("kri.auth.jwt.secret must be at least 32 bytes (UTF-8) for HS256"); throw new IllegalStateException(
"kri.auth.jwt.secret must be at least 32 bytes (UTF-8) for HS256");
} }
// secret 문자열을 HMAC 키로 전환 // secret 문자열을 HMAC 키로 전환
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
@@ -69,11 +76,10 @@ public class JwtService {
// ====================================================== // ======================================================
// 토큰 생성 (DTO 기반) // 토큰 생성 (DTO 기반)
// ====================================================== // ======================================================
/** /**
* JwtUserClaimsDto 기반 Access Token 생성 * JwtUserClaimsDto 기반 Access Token 생성 - subject = userId - claims: userId, userCmpn, userTeam,
* - subject = userId * userName, role
* - claims:
* userId, userCmpn, userTeam, userName, role
*/ */
public String generateAccessToken(JwtUserClaimsDto userClaims) { public String generateAccessToken(JwtUserClaimsDto userClaims) {
Map<String, Object> claims = buildClaims(userClaims); Map<String, Object> claims = buildClaims(userClaims);
@@ -157,11 +163,8 @@ public class JwtService {
// ====================================================== // ======================================================
/** /**
* DTO → Spring Security Authentication 변환 * DTO → Spring Security Authentication 변환 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성. ex) role =
* 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성. * 1 → "ROLE_1" 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면, 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨.
* ex) role = 1 → "ROLE_1"
* 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면,
* 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨.
*/ */
public Authentication toAuthentication(JwtUserClaimsDto dto) { public Authentication toAuthentication(JwtUserClaimsDto dto) {
String principal = dto.getUserId(); String principal = dto.getUserId();

View File

@@ -1,25 +1,30 @@
package com.kri.common.auth.persistence.entity; package com.kri.common.auth.persistence.entity;
import jakarta.persistence.*; import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDateTime;
import java.util.Map;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes; import org.hibernate.type.SqlTypes;
import java.time.LocalDateTime;
import java.util.Map;
@Getter @Getter
@Setter @Setter
@Entity @Entity
@Table(name = "t_api_key") @Table(name = "t_api_key")
public class TApiKeyEntity { public class TApiKeyEntity {
@Id @Id
@Column(name = "api_key", nullable = false, length = 256) @Column(name = "api_key", nullable = false, length = 256)
private String apiKey; private String apiKey;
/** 1=ACTIVE, 0=REVOKED */ /**
* 1=ACTIVE, 0=REVOKED
*/
@Column(name = "status", nullable = false) @Column(name = "status", nullable = false)
@ColumnDefault("1") @ColumnDefault("1")
private Short status; private Short status;

View File

@@ -11,10 +11,15 @@ import lombok.Setter;
@Entity @Entity
@Table(name = "t_api_key_service_map") @Table(name = "t_api_key_service_map")
public class TApiKeyServiceMapEntity { public class TApiKeyServiceMapEntity {
@EmbeddedId @EmbeddedId
private TApiKeyServiceMapEntityId id; private TApiKeyServiceMapEntityId id;
public String getApiKey() { return id.getApiKey(); } public String getApiKey() {
return id.getApiKey();
}
public String getServiceCode() { return id.getServiceCode(); } public String getServiceCode() {
return id.getServiceCode();
}
} }

View File

@@ -3,17 +3,17 @@ package com.kri.common.auth.persistence.entity;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Embeddable; import jakarta.persistence.Embeddable;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Objects;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import java.io.Serializable;
import java.util.Objects;
@Getter @Getter
@Setter @Setter
@Embeddable @Embeddable
public class TApiKeyServiceMapEntityId implements Serializable { public class TApiKeyServiceMapEntityId implements Serializable {
@NotNull @NotNull
@Column(name = "api_key", nullable = false, length = 256) @Column(name = "api_key", nullable = false, length = 256)
private String apiKey; private String apiKey;
@@ -24,8 +24,12 @@ public class TApiKeyServiceMapEntityId implements Serializable {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; return true;
}
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
return false;
}
TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o; TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o;
return Objects.equals(this.apiKey, entity.apiKey) && return Objects.equals(this.apiKey, entity.apiKey) &&
Objects.equals(this.serviceCode, entity.serviceCode); Objects.equals(this.serviceCode, entity.serviceCode);

View File

@@ -1,19 +1,21 @@
package com.kri.common.auth.persistence.repository; package com.kri.common.auth.persistence.repository;
import com.kri.common.auth.persistence.entity.TApiKeyEntity; import com.kri.common.auth.persistence.entity.TApiKeyEntity;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import java.util.List;
public interface ApiKeyRepository extends JpaRepository<TApiKeyEntity, String> { public interface ApiKeyRepository extends JpaRepository<TApiKeyEntity, String> {
/** ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에 */
/**
* ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에
*/
@Query(""" @Query("""
select a select a
from TApiKeyEntity a from TApiKeyEntity a
join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey
where a.status = 1 and m.id.serviceCode = :serviceCode where a.status = 1 and m.id.serviceCode = :serviceCode
""") """)
List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode")String serviceCode); List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode") String serviceCode);
} }

View File

@@ -1,24 +1,25 @@
package com.kri.common.cache; package com.kri.common.cache;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractListCache<T> { public abstract class AbstractListCache<T> {
private List<T> list = List.of();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private List<T> list = List.of();
@EventListener(ApplicationReadyEvent.class) @EventListener(ApplicationReadyEvent.class)
@Transactional(readOnly = true) @Transactional(readOnly = true)
public void loadOnStartup() { public void loadOnStartup() {
List<T> tempList = loadFromDb(); List<T> tempList = loadFromDb();
if(tempList != null) setList(tempList); if (tempList != null) {
setList(tempList);
}
} }
public List<T> getList() { public List<T> getList() {
@@ -30,25 +31,6 @@ public abstract class AbstractListCache<T> {
} }
} }
@Transactional(readOnly = true)
public List<T> reload() {
List<T> tempList = loadFromDb();
if(tempList == null) {
throw new UnsupportedOperationException("This cache does not support reload().");
}
setList(tempList);
return getList();
}
public List<T> clear() {
lock.writeLock().lock();
try{
return list = List.of();
} finally {
lock.writeLock().unlock();
}
}
public void setList(List<T> next) { public void setList(List<T> next) {
lock.writeLock().lock(); lock.writeLock().lock();
try { try {
@@ -58,8 +40,29 @@ public abstract class AbstractListCache<T> {
} }
} }
@Transactional(readOnly = true)
public List<T> reload() {
List<T> tempList = loadFromDb();
if (tempList == null) {
throw new UnsupportedOperationException("This cache does not support reload().");
}
setList(tempList);
return getList();
}
public List<T> clear() {
lock.writeLock().lock();
try {
return list = List.of();
} finally {
lock.writeLock().unlock();
}
}
public void addAll(List<T> items) { public void addAll(List<T> items) {
if (items == null || items.isEmpty()) return; if (items == null || items.isEmpty()) {
return;
}
lock.writeLock().lock(); lock.writeLock().lock();
try { try {
List<T> merged = new java.util.ArrayList<>(this.list); List<T> merged = new java.util.ArrayList<>(this.list);
@@ -71,7 +74,9 @@ public abstract class AbstractListCache<T> {
} }
public void addAll(int index, Collection<? extends T> items) { public void addAll(int index, Collection<? extends T> items) {
if (items == null || items.isEmpty()) return; if (items == null || items.isEmpty()) {
return;
}
lock.writeLock().lock(); lock.writeLock().lock();
try { try {
@@ -95,10 +100,10 @@ public abstract class AbstractListCache<T> {
} }
} }
public void add(int index, T item){ public void add(int index, T item) {
lock.writeLock().lock(); lock.writeLock().lock();
try{ try {
ArrayList<T> next = new ArrayList<>(this.list); ArrayList<T> next = new ArrayList<>(this.list);
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정 int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
next.add(i, item); next.add(i, item);

View File

@@ -1,23 +1,24 @@
package com.kri.common.cache; package com.kri.common.cache;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractMapCache<K, V> { public abstract class AbstractMapCache<K, V> {
private Map<K, V> map = Map.of();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private Map<K, V> map = Map.of();
@EventListener(ApplicationReadyEvent.class) @EventListener(ApplicationReadyEvent.class)
@Transactional(readOnly = true) @Transactional(readOnly = true)
public void loadOnStartup() { public void loadOnStartup() {
Map<K, V> tempMap = loadFromDb(); Map<K, V> tempMap = loadFromDb();
if(tempMap != null) setMap(tempMap); if (tempMap != null) {
setMap(tempMap);
}
} }
public Map<K, V> getMap() { public Map<K, V> getMap() {
@@ -29,6 +30,18 @@ public abstract class AbstractMapCache<K, V> {
} }
} }
/**
* 수동: 전체 교체(불변 스냅샷으로 보관)
*/
public void setMap(Map<K, V> next) {
lock.writeLock().lock();
try {
this.map = Map.copyOf(next == null ? Map.of() : next);
} finally {
lock.writeLock().unlock();
}
}
public V get(K key) { public V get(K key) {
lock.readLock().lock(); lock.readLock().lock();
try { try {
@@ -50,23 +63,13 @@ public abstract class AbstractMapCache<K, V> {
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Map<K, V> reload() { public Map<K, V> reload() {
Map<K, V> tempMap = loadFromDb(); Map<K, V> tempMap = loadFromDb();
if(tempMap == null) { if (tempMap == null) {
throw new UnsupportedOperationException("This cache does not support reload()."); throw new UnsupportedOperationException("This cache does not support reload().");
} }
setMap(tempMap); setMap(tempMap);
return getMap(); return getMap();
} }
/** 수동: 전체 교체(불변 스냅샷으로 보관) */
public void setMap(Map<K, V> next) {
lock.writeLock().lock();
try {
this.map = Map.copyOf(next == null ? Map.of() : next);
} finally {
lock.writeLock().unlock();
}
}
public void put(K key, V value) { public void put(K key, V value) {
lock.writeLock().lock(); lock.writeLock().lock();
try { try {
@@ -78,9 +81,13 @@ public abstract class AbstractMapCache<K, V> {
} }
} }
/** 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체) */ /**
* 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체)
*/
public void putAll(Map<K, V> entries) { public void putAll(Map<K, V> entries) {
if (entries == null || entries.isEmpty()) return; if (entries == null || entries.isEmpty()) {
return;
}
lock.writeLock().lock(); lock.writeLock().lock();
try { try {
@@ -92,7 +99,9 @@ public abstract class AbstractMapCache<K, V> {
} }
} }
/** clear: 완전 비우기 */ /**
* clear: 완전 비우기
*/
public void clear() { public void clear() {
lock.writeLock().lock(); lock.writeLock().lock();
try { try {

View File

@@ -1,50 +1,69 @@
package com.kri.common.datetime; package com.kri.common.datetime;
import java.time.*; import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException; import java.time.format.DateTimeParseException;
import java.util.Objects; import java.util.Objects;
public final class DateTimeUtil { public final class DateTimeUtil {
private DateTimeUtil() {}
public static final ZoneId KST = ZoneId.of("Asia/Seoul"); public static final ZoneId KST = ZoneId.of("Asia/Seoul");
public static final ZoneId UTC = ZoneOffset.UTC; public static final ZoneId UTC = ZoneOffset.UTC;
/**
/** 날짜+시간: 2025-11-28 15:00:14 */ * 날짜+시간: 2025-11-28 15:00:14
*/
public static final DateTimeFormatter DATETIME_FMT = public static final DateTimeFormatter DATETIME_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
/** 날짜: 2025-11-28 */ * 날짜: 2025-11-28
*/
public static final DateTimeFormatter DATE_FMT = public static final DateTimeFormatter DATE_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd"); DateTimeFormatter.ofPattern("yyyy-MM-dd");
private DateTimeUtil() {
}
/* ======================= /* =======================
* Now (KST) * Now (KST)
* ======================= */ * ======================= */
/** 현재 KST 날짜+시간 문자열 */ /**
* 현재 KST 날짜+시간 문자열
*/
public static String nowKstDateTime() { public static String nowKstDateTime() {
return formatKst(Instant.now(), DATETIME_FMT); return formatKst(Instant.now(), DATETIME_FMT);
} }
/** 현재 KST 날짜 문자열 */ /**
* 현재 KST 날짜 문자열
*/
public static String nowKstDate() { public static String nowKstDate() {
return nowKstZoned().format(DATE_FMT); return nowKstZoned().format(DATE_FMT);
} }
/** 현재 KST ZonedDateTime */ /**
* 현재 KST ZonedDateTime
*/
public static ZonedDateTime nowKstZoned() { public static ZonedDateTime nowKstZoned() {
return Instant.now().atZone(KST); return Instant.now().atZone(KST);
} }
/** 현재 KST LocalDateTime */ /**
* 현재 KST LocalDateTime
*/
public static LocalDateTime nowKstLocalDateTime() { public static LocalDateTime nowKstLocalDateTime() {
return nowKstZoned().toLocalDateTime(); return nowKstZoned().toLocalDateTime();
} }
/** 현재 KST LocalDate */ /**
* 현재 KST LocalDate
*/
public static LocalDate nowKstLocalDate() { public static LocalDate nowKstLocalDate() {
return nowKstZoned().toLocalDate(); return nowKstZoned().toLocalDate();
} }
@@ -53,19 +72,27 @@ public final class DateTimeUtil {
* Format (Instant -> String) * Format (Instant -> String)
* ======================= */ * ======================= */
/** Instant -> KST 날짜+시간 문자열 */ /**
* Instant -> KST 날짜+시간 문자열
*/
public static String formatKstDateTime(Instant instant) { public static String formatKstDateTime(Instant instant) {
return formatKst(instant, DATETIME_FMT); return formatKst(instant, DATETIME_FMT);
} }
/** Instant -> KST 날짜 문자열 */ /**
* Instant -> KST 날짜 문자열
*/
public static String formatKstDate(Instant instant) { public static String formatKstDate(Instant instant) {
return formatKst(instant, DATE_FMT); return formatKst(instant, DATE_FMT);
} }
/** Instant -> KST 문자열 (커스텀 포맷) */ /**
* Instant -> KST 문자열 (커스텀 포맷)
*/
public static String formatKst(Instant instant, DateTimeFormatter formatter) { public static String formatKst(Instant instant, DateTimeFormatter formatter) {
if (instant == null) return null; if (instant == null) {
return null;
}
final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT; final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT;
return instant.atZone(KST).format(fmt); return instant.atZone(KST).format(fmt);
} }
@@ -74,24 +101,44 @@ public final class DateTimeUtil {
* Validate * Validate
* ======================= */ * ======================= */
/** "yyyy-MM-dd" 형태인지 */ /**
* "yyyy-MM-dd" 형태인지
*/
public static boolean isDate(String text) { public static boolean isDate(String text) {
return tryParseLocalDate(text, DATE_FMT) != null; return tryParseLocalDate(text, DATE_FMT) != null;
} }
/** "yyyy-MM-dd HH:mm:ss" 형태인지 */ /**
* "yyyy-MM-dd HH:mm:ss" 형태인지
*/
public static boolean isDateTime(String text) { public static boolean isDateTime(String text) {
return tryParseLocalDateTime(text, DATETIME_FMT) != null; return tryParseLocalDateTime(text, DATETIME_FMT) != null;
} }
/** ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지 */ /**
* ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지
*/
public static boolean isIsoDateTime(String text) { public static boolean isIsoDateTime(String text) {
if (text == null || text.isBlank()) return false; if (text == null || text.isBlank()) {
return false;
}
final String s = text.trim(); final String s = text.trim();
try { Instant.parse(s); return true; } catch (DateTimeParseException ignored) {} try {
try { OffsetDateTime.parse(s); return true; } catch (DateTimeParseException ignored) {} Instant.parse(s);
try { ZonedDateTime.parse(s); return true; } catch (DateTimeParseException ignored) {} return true;
} catch (DateTimeParseException ignored) {
}
try {
OffsetDateTime.parse(s);
return true;
} catch (DateTimeParseException ignored) {
}
try {
ZonedDateTime.parse(s);
return true;
} catch (DateTimeParseException ignored) {
}
return false; return false;
} }
@@ -100,38 +147,58 @@ public final class DateTimeUtil {
* Parse (String -> Instant) * Parse (String -> Instant)
* ======================= */ * ======================= */
/** ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도) */ /**
* ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도)
*/
public static Instant parseToInstant(String text) { public static Instant parseToInstant(String text) {
if (text == null || text.isBlank()) return null; if (text == null || text.isBlank()) {
return null;
}
final String s = text.trim(); final String s = text.trim();
try { return Instant.parse(s); } catch (DateTimeParseException ignored) {} try {
try { return OffsetDateTime.parse(s).toInstant(); } catch (DateTimeParseException ignored) {} return Instant.parse(s);
try { return ZonedDateTime.parse(s).toInstant(); } catch (DateTimeParseException ignored) {} } catch (DateTimeParseException ignored) {
}
try {
return OffsetDateTime.parse(s).toInstant();
} catch (DateTimeParseException ignored) {
}
try {
return ZonedDateTime.parse(s).toInstant();
} catch (DateTimeParseException ignored) {
}
throw new DateTimeParseException("Unsupported datetime format", s, 0); throw new DateTimeParseException("Unsupported datetime format", s, 0);
} }
/** /**
* 커스텀 포맷 문자열을 KST 기준으로 해석해서 Instant로 변환 * 커스텀 포맷 문자열을 KST 기준으로 해석해서 Instant로 변환 예) "2025-11-28 15:00:14", formatter=DATETIME_FMT
* 예) "2025-11-28 15:00:14", formatter=DATETIME_FMT
*/ */
public static Instant parseKstToInstant(String text, DateTimeFormatter formatter) { public static Instant parseKstToInstant(String text, DateTimeFormatter formatter) {
if (text == null || text.isBlank()) return null; if (text == null || text.isBlank()) {
return null;
}
Objects.requireNonNull(formatter, "formatter"); Objects.requireNonNull(formatter, "formatter");
LocalDateTime ldt = LocalDateTime.parse(text.trim(), formatter); LocalDateTime ldt = LocalDateTime.parse(text.trim(), formatter);
return ldt.atZone(KST).toInstant(); return ldt.atZone(KST).toInstant();
} }
/** "yyyy-MM-dd HH:mm:ss" 포맷을 KST로 해석 */ /**
* "yyyy-MM-dd HH:mm:ss" 포맷을 KST로 해석
*/
public static Instant parseKstDateTimeToInstant(String text) { public static Instant parseKstDateTimeToInstant(String text) {
return parseKstToInstant(text, DATETIME_FMT); return parseKstToInstant(text, DATETIME_FMT);
} }
/** "yyyy-MM-dd" 포맷을 KST 자정(00:00:00)으로 해석 */ /**
* "yyyy-MM-dd" 포맷을 KST 자정(00:00:00)으로 해석
*/
public static Instant parseKstDateToInstant(String text) { public static Instant parseKstDateToInstant(String text) {
if (text == null || text.isBlank()) return null; if (text == null || text.isBlank()) {
return null;
}
LocalDate ld = LocalDate.parse(text.trim(), DATE_FMT); LocalDate ld = LocalDate.parse(text.trim(), DATE_FMT);
return ld.atStartOfDay(KST).toInstant(); return ld.atStartOfDay(KST).toInstant();
} }
@@ -140,26 +207,36 @@ public final class DateTimeUtil {
* Convert / Helpers * Convert / Helpers
* ======================= */ * ======================= */
/** Instant -> KST ZonedDateTime */ /**
* Instant -> KST ZonedDateTime
*/
public static ZonedDateTime toKstZoned(Instant instant) { public static ZonedDateTime toKstZoned(Instant instant) {
return instant == null ? null : instant.atZone(KST); return instant == null ? null : instant.atZone(KST);
} }
/** Instant -> KST LocalDateTime */ /**
* Instant -> KST LocalDateTime
*/
public static LocalDateTime toKstLocalDateTime(Instant instant) { public static LocalDateTime toKstLocalDateTime(Instant instant) {
ZonedDateTime zdt = toKstZoned(instant); ZonedDateTime zdt = toKstZoned(instant);
return zdt == null ? null : zdt.toLocalDateTime(); return zdt == null ? null : zdt.toLocalDateTime();
} }
/** Instant -> KST LocalDate */ /**
* Instant -> KST LocalDate
*/
public static LocalDate toKstLocalDate(Instant instant) { public static LocalDate toKstLocalDate(Instant instant) {
ZonedDateTime zdt = toKstZoned(instant); ZonedDateTime zdt = toKstZoned(instant);
return zdt == null ? null : zdt.toLocalDate(); return zdt == null ? null : zdt.toLocalDate();
} }
/** null/blank 안전 trim */ /**
* null/blank 안전 trim
*/
public static String trimToNull(String s) { public static String trimToNull(String s) {
if (s == null) return null; if (s == null) {
return null;
}
String t = s.trim(); String t = s.trim();
return t.isEmpty() ? null : t; return t.isEmpty() ? null : t;
} }
@@ -173,14 +250,24 @@ public final class DateTimeUtil {
} }
private static LocalDate tryParseLocalDate(String text, DateTimeFormatter fmt) { private static LocalDate tryParseLocalDate(String text, DateTimeFormatter fmt) {
if (text == null || text.isBlank()) return null; if (text == null || text.isBlank()) {
try { return LocalDate.parse(text.trim(), fmt); } return null;
catch (DateTimeParseException e) { return null; } }
try {
return LocalDate.parse(text.trim(), fmt);
} catch (DateTimeParseException e) {
return null;
}
} }
private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) { private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) {
if (text == null || text.isBlank()) return null; if (text == null || text.isBlank()) {
try { return LocalDateTime.parse(text.trim(), fmt); } return null;
catch (DateTimeParseException e) { return null; } }
try {
return LocalDateTime.parse(text.trim(), fmt);
} catch (DateTimeParseException e) {
return null;
}
} }
} }

View File

@@ -2,8 +2,11 @@ package com.kri.common.datetime;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.lang.annotation.Documented;
import java.lang.annotation.*; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer; import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.IOException; import java.io.IOException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@@ -62,12 +61,15 @@ public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDate
@Override @Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String s = DateTimeUtil.trimToNull(p.getText()); String s = DateTimeUtil.trimToNull(p.getText());
if (s == null) return null; if (s == null) {
return null;
}
for (DateTimeFormatter f : formatters) { for (DateTimeFormatter f : formatters) {
try { try {
return LocalDateTime.parse(s, f); return LocalDateTime.parse(s, f);
} catch (DateTimeParseException ignored) {} } catch (DateTimeParseException ignored) {
}
} }
throw ctxt.weirdStringException(s, LocalDateTime.class, throw ctxt.weirdStringException(s, LocalDateTime.class,
@@ -77,10 +79,14 @@ public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDate
@Override @Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
throws JsonMappingException { throws JsonMappingException {
if (property == null) return this; if (property == null) {
return this;
}
LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class); LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class);
if (ann == null) ann = property.getContextAnnotation(LenientLocalDateTime.class); if (ann == null) {
ann = property.getContextAnnotation(LenientLocalDateTime.class);
}
return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns()); return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns());
} }

View File

@@ -1,5 +1,6 @@
package com.kri.common.enums; package com.kri.common.enums;
public interface CodeEnum<T> { public interface CodeEnum<T> {
T getCode(); T getCode();
} }

View File

@@ -2,10 +2,13 @@ package com.kri.common.enums;
public final class CodeEnumUtils { public final class CodeEnumUtils {
private CodeEnumUtils() {} private CodeEnumUtils() {
}
public static <E extends Enum<E> & CodeEnum<V>, V> E fromCode(Class<E> enumClass, V code) { public static <E extends Enum<E> & CodeEnum<V>, V> E fromCode(Class<E> enumClass, V code) {
if (code == null) return null; if (code == null) {
return null;
}
for (E e : enumClass.getEnumConstants()) { for (E e : enumClass.getEnumConstants()) {
if (e.getCode().equals(code)) { if (e.getCode().equals(code)) {

View File

@@ -1,11 +1,17 @@
package com.kri.common.excel; package com.kri.common.excel;
import java.lang.annotation.*; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) @Target(ElementType.FIELD)
public @interface ExcelColumn { public @interface ExcelColumn {
String header(); // 엑셀 헤더 이름 String header(); // 엑셀 헤더 이름
int order() default 0; // 컬럼 순서 int order() default 0; // 컬럼 순서
int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로 int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로
} }

View File

@@ -1,7 +1,25 @@
package com.kri.common.excel; package com.kri.common.excel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.model.SharedStringsTable;
@@ -13,18 +31,11 @@ import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.helpers.XMLReaderFactory;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.*;
/** /**
* Excel <-> 객체/맵 변환 유틸리티 * Excel <-> 객체/맵 변환 유틸리티
* * <p>
* 전제: * 전제: - DTO 필드는 @ExcelColumn(header = "헤더명", order = 0) 형태로 어노테이션을 단다. - 셀 값 파싱은
* - DTO 필드는 @ExcelColumn(header = "헤더명", order = 0) 형태로 어노테이션을 단다. * ExcelUtil.getStringCell(Cell) 사용.
* - 셀 값 파싱은 ExcelUtil.getStringCell(Cell) 사용.
*/ */
public final class ExcelMapper { public final class ExcelMapper {
@@ -107,14 +118,18 @@ public final class ExcelMapper {
for (int r = 1; r <= lastRowNum; r++) { for (int r = 1; r <= lastRowNum; r++) {
Row row = sheet.getRow(r); Row row = sheet.getRow(r);
if (row == null) continue; if (row == null) {
continue;
}
try { try {
T instance = clazz.getDeclaredConstructor().newInstance(); T instance = clazz.getDeclaredConstructor().newInstance();
for (ExcelFieldMeta meta : fields) { for (ExcelFieldMeta meta : fields) {
Integer colIdx = headerIndexMap.get(meta.header()); Integer colIdx = headerIndexMap.get(meta.header());
if (colIdx == null) continue; if (colIdx == null) {
continue;
}
Cell cell = row.getCell(colIdx); Cell cell = row.getCell(colIdx);
String cellValue = ExcelUtil.getStringCell(cell); String cellValue = ExcelUtil.getStringCell(cell);
@@ -159,7 +174,9 @@ public final class ExcelMapper {
for (int r = 1; r <= lastRow; r++) { for (int r = 1; r <= lastRow; r++) {
Row row = sheet.getRow(r); Row row = sheet.getRow(r);
if (row == null) continue; if (row == null) {
continue;
}
Map<String, String> rowMap = new LinkedHashMap<>(); Map<String, String> rowMap = new LinkedHashMap<>();
boolean allBlank = true; boolean allBlank = true;
@@ -214,7 +231,9 @@ public final class ExcelMapper {
int rowIndex = 1; int rowIndex = 1;
for (Map<String, ?> rowMap : rows) { for (Map<String, ?> rowMap : rows) {
Row row = sheet.createRow(rowIndex++); Row row = sheet.createRow(rowIndex++);
if (rowMap == null) continue; if (rowMap == null) {
continue;
}
for (int c = 0; c < headers.size(); c++) { for (int c = 0; c < headers.size(); c++) {
String key = headers.get(c); String key = headers.get(c);
@@ -291,7 +310,8 @@ public final class ExcelMapper {
* 5-1. Streaming Append Writer (SXSSFWorkbook) - DTO 기반 (chunk 지원) * 5-1. Streaming Append Writer (SXSSFWorkbook) - DTO 기반 (chunk 지원)
* ========================================================= */ * ========================================================= */
public static <T> StreamingWriter<T> openStreamingWriter(Class<T> clazz, int rowAccessWindowSize) { public static <T> StreamingWriter<T> openStreamingWriter(Class<T> clazz,
int rowAccessWindowSize) {
SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
Sheet sheet = workbook.createSheet("Sheet1"); Sheet sheet = workbook.createSheet("Sheet1");
@@ -311,60 +331,6 @@ public final class ExcelMapper {
return new StreamingWriter<>(workbook, sheet, fields, 1); return new StreamingWriter<>(workbook, sheet, fields, 1);
} }
/**
* chunk 단위로 append 가능한 SXSSF Writer
* - rowAccessWindowSize 만큼만 메모리에 유지하고 나머지는 temp file로 flush
* - 마지막에 writeTo(OutputStream) 한 번 호출로 XLSX 완성
*/
public static final class StreamingWriter<T> implements AutoCloseable {
private final SXSSFWorkbook workbook;
private final Sheet sheet;
private final List<ExcelFieldMeta> fields;
private int rowIndex;
private StreamingWriter(SXSSFWorkbook workbook, Sheet sheet, List<ExcelFieldMeta> fields, int rowIndex) {
this.workbook = workbook;
this.sheet = sheet;
this.fields = fields;
this.rowIndex = rowIndex;
}
public void append(T item) {
if (item == null) return;
Row row = sheet.createRow(rowIndex++);
for (ExcelFieldMeta meta : fields) {
Cell cell = row.createCell(meta.order());
Object value = meta.getValue(item);
if (value != null) cell.setCellValue(value.toString());
else cell.setBlank();
}
}
public void appendAll(Collection<T> items) {
if (items == null || items.isEmpty()) return;
for (T item : items) append(item);
}
/** XLSX는 마지막에 한 번 write 해야 파일이 완성됩니다. */
public void writeTo(OutputStream out) throws IOException {
workbook.write(out);
out.flush();
}
@Override
public void close() throws IOException {
// SXSSF temp 파일 제거
workbook.dispose();
workbook.close();
}
}
/* =========================================================
* 6. Streaming Write (SXSSFWorkbook) - Map 기반
* ========================================================= */
public static SXSSFWorkbook writeStreamingFromMap(List<? extends Map<String, ?>> rows, public static SXSSFWorkbook writeStreamingFromMap(List<? extends Map<String, ?>> rows,
int rowAccessWindowSize) { int rowAccessWindowSize) {
SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize); SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
@@ -393,7 +359,9 @@ public final class ExcelMapper {
int rowIndex = 1; int rowIndex = 1;
for (Map<String, ?> rowMap : rows) { for (Map<String, ?> rowMap : rows) {
Row row = sheet.createRow(rowIndex++); Row row = sheet.createRow(rowIndex++);
if (rowMap == null) continue; if (rowMap == null) {
continue;
}
for (int c = 0; c < headers.size(); c++) { for (int c = 0; c < headers.size(); c++) {
String key = headers.get(c); String key = headers.get(c);
@@ -407,23 +375,13 @@ public final class ExcelMapper {
return workbook; return workbook;
} }
/* ========================================================= /* =========================================================
* 7. Streaming Read (XSSFReader + SAX) -> RowMapHandler * 6. Streaming Write (SXSSFWorkbook) - Map 기반
* ========================================================= */ * ========================================================= */
@FunctionalInterface
public interface RowMapHandler {
/** /**
* @param row 헤더명 -> 값 맵 (1행은 헤더라서 콜백 X, 2행부터 데이터) * XSSFReader + SAX 기반 스트리밍 읽기. - 첫 번째 시트만 읽음. - 1행은 헤더, 2행부터 데이터로 가정.
* @param rowIndex 엑셀 실제 행 번호 (1-based)
*/
void handleRow(Map<String, String> row, int rowIndex);
}
/**
* XSSFReader + SAX 기반 스트리밍 읽기.
* - 첫 번째 시트만 읽음.
* - 1행은 헤더, 2행부터 데이터로 가정.
*/ */
public static void readStreaming(InputStream inputStream, RowMapHandler handler) { public static void readStreaming(InputStream inputStream, RowMapHandler handler) {
try { try {
@@ -449,20 +407,163 @@ public final class ExcelMapper {
} }
} }
/* =========================================================
* 7. Streaming Read (XSSFReader + SAX) -> RowMapHandler
* ========================================================= */
private static List<ExcelFieldMeta> getExcelFields(Class<?> clazz) {
List<ExcelFieldMeta> result = new ArrayList<>();
for (Class<?> c = clazz; c != null && c != Object.class; c = c.getSuperclass()) {
for (Field field : c.getDeclaredFields()) {
ExcelColumn ann = field.getAnnotation(ExcelColumn.class);
if (ann == null) {
continue;
}
field.setAccessible(true);
result.add(new ExcelFieldMeta(field, ann.header(), ann.order(), ann.width()));
}
}
result.sort(Comparator.comparingInt(ExcelFieldMeta::order));
return result;
}
private static void setFieldValue(Object target, Field field, String value)
throws IllegalAccessException {
Class<?> type = field.getType();
// 1) null 또는 공백 처리
if (value == null || value.isBlank()) {
// primitive 타입이면 기본값 유지 (0, false 등) → 그냥 리턴
if (type.isPrimitive()) {
return;
}
// 래퍼 타입(String, Integer, Long, Boolean, ...)이면 null 세팅
field.set(target, null);
return;
}
String trimmed = value.trim();
try {
if (type == String.class) {
field.set(target, trimmed);
} else if (type == Integer.class || type == int.class) {
field.set(target, Integer.parseInt(trimmed));
} else if (type == Long.class || type == long.class) {
field.set(target, Long.parseLong(trimmed));
} else if (type == Boolean.class || type == boolean.class) {
// "true"/"false" 외에 "Y"/"N" 같은 것도 처리하고 싶으면 여기서 추가 가능
field.set(target, Boolean.parseBoolean(trimmed));
} else {
// TODO: 필요 시 LocalDate, BigDecimal 등 타입 확장
field.set(target, trimmed);
}
} catch (NumberFormatException e) {
// 어디서 어떤 값 때문에 깨졌는지 로그/예외에 남겨두면 디버깅 편함
throw new RuntimeException(
"엑셀 값 파싱 실패: field=" + field.getName() +
", type=" + type.getSimpleName() +
", value='" + value + "'",
e
);
}
}
@FunctionalInterface
public interface RowMapHandler {
/**
* @param row 헤더명 -> 값 맵 (1행은 헤더라서 콜백 X, 2행부터 데이터)
* @param rowIndex 엑셀 실제 행 번호 (1-based)
*/
void handleRow(Map<String, String> row, int rowIndex);
}
/* =========================================================
* 8. 내부 메타 수집 & 필드 세터
* ========================================================= */
/**
* chunk 단위로 append 가능한 SXSSF Writer - rowAccessWindowSize 만큼만 메모리에 유지하고 나머지는 temp file로 flush -
* 마지막에 writeTo(OutputStream) 한 번 호출로 XLSX 완성
*/
public static final class StreamingWriter<T> implements AutoCloseable {
private final SXSSFWorkbook workbook;
private final Sheet sheet;
private final List<ExcelFieldMeta> fields;
private int rowIndex;
private StreamingWriter(SXSSFWorkbook workbook, Sheet sheet, List<ExcelFieldMeta> fields,
int rowIndex) {
this.workbook = workbook;
this.sheet = sheet;
this.fields = fields;
this.rowIndex = rowIndex;
}
public void append(T item) {
if (item == null) {
return;
}
Row row = sheet.createRow(rowIndex++);
for (ExcelFieldMeta meta : fields) {
Cell cell = row.createCell(meta.order());
Object value = meta.getValue(item);
if (value != null) {
cell.setCellValue(value.toString());
} else {
cell.setBlank();
}
}
}
public void appendAll(Collection<T> items) {
if (items == null || items.isEmpty()) {
return;
}
for (T item : items) {
append(item);
}
}
/**
* XLSX는 마지막에 한 번 write 해야 파일이 완성됩니다.
*/
public void writeTo(OutputStream out) throws IOException {
workbook.write(out);
out.flush();
}
@Override
public void close() throws IOException {
// SXSSF temp 파일 제거
workbook.dispose();
workbook.close();
}
}
/** /**
* SAX 핸들러: 한 행을 Map<String,String> 으로 만들어 RowMapHandler에 전달. * SAX 핸들러: 한 행을 Map<String,String> 으로 만들어 RowMapHandler에 전달.
*/ */
private static class SheetToMapHandler extends DefaultHandler { private static class SheetToMapHandler extends DefaultHandler {
private final SharedStringsTable sst; private final SharedStringsTable sst;
private final RowMapHandler handler; private final RowMapHandler handler;
private final Map<Integer, String> cellMap = new HashMap<>();
private int currentRowNum; private int currentRowNum;
private String currentCellRef; private String currentCellRef;
private String currentCellType; private String currentCellType;
private StringBuilder currentValue; private StringBuilder currentValue;
private boolean isValueOpen; private boolean isValueOpen;
private final Map<Integer, String> cellMap = new HashMap<>();
private List<String> headers = new ArrayList<>(); private List<String> headers = new ArrayList<>();
private boolean headerProcessed = false; private boolean headerProcessed = false;
@@ -523,7 +624,9 @@ public final class ExcelMapper {
} }
headerProcessed = true; headerProcessed = true;
} else { } else {
if (headers == null || headers.isEmpty()) return; if (headers == null || headers.isEmpty()) {
return;
}
Map<String, String> rowMap = new LinkedHashMap<>(); Map<String, String> rowMap = new LinkedHashMap<>();
boolean allBlank = true; boolean allBlank = true;
@@ -557,73 +660,8 @@ public final class ExcelMapper {
} }
} }
/* =========================================================
* 8. 내부 메타 수집 & 필드 세터
* ========================================================= */
private static List<ExcelFieldMeta> getExcelFields(Class<?> clazz) {
List<ExcelFieldMeta> result = new ArrayList<>();
for (Class<?> c = clazz; c != null && c != Object.class; c = c.getSuperclass()) {
for (Field field : c.getDeclaredFields()) {
ExcelColumn ann = field.getAnnotation(ExcelColumn.class);
if (ann == null) continue;
field.setAccessible(true);
result.add(new ExcelFieldMeta(field, ann.header(), ann.order(), ann.width()));
}
}
result.sort(Comparator.comparingInt(ExcelFieldMeta::order));
return result;
}
private static void setFieldValue(Object target, Field field, String value) throws IllegalAccessException {
Class<?> type = field.getType();
// 1) null 또는 공백 처리
if (value == null || value.isBlank()) {
// primitive 타입이면 기본값 유지 (0, false 등) → 그냥 리턴
if (type.isPrimitive()) {
return;
}
// 래퍼 타입(String, Integer, Long, Boolean, ...)이면 null 세팅
field.set(target, null);
return;
}
String trimmed = value.trim();
try {
if (type == String.class) {
field.set(target, trimmed);
} else if (type == Integer.class || type == int.class) {
field.set(target, Integer.parseInt(trimmed));
} else if (type == Long.class || type == long.class) {
field.set(target, Long.parseLong(trimmed));
} else if (type == Boolean.class || type == boolean.class) {
// "true"/"false" 외에 "Y"/"N" 같은 것도 처리하고 싶으면 여기서 추가 가능
field.set(target, Boolean.parseBoolean(trimmed));
} else {
// TODO: 필요 시 LocalDate, BigDecimal 등 타입 확장
field.set(target, trimmed);
}
} catch (NumberFormatException e) {
// 어디서 어떤 값 때문에 깨졌는지 로그/예외에 남겨두면 디버깅 편함
throw new RuntimeException(
"엑셀 값 파싱 실패: field=" + field.getName() +
", type=" + type.getSimpleName() +
", value='" + value + "'",
e
);
}
}
private record ExcelFieldMeta(Field field, String header, int order, int width) { private record ExcelFieldMeta(Field field, String header, int order, int width) {
Object getValue(Object target) { Object getValue(Object target) {
try { try {
return field.get(target); return field.get(target);

View File

@@ -1,14 +1,12 @@
package com.kri.common.excel; package com.kri.common.excel;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.ss.usermodel.DateUtil;
import java.lang.reflect.Field;
import java.util.*;
public final class ExcelUtil { public final class ExcelUtil {
private ExcelUtil() {} private ExcelUtil() {
}
public static String getStringCell(Cell cell) { public static String getStringCell(Cell cell) {
if (cell == null) { if (cell == null) {

View File

@@ -3,6 +3,7 @@ package com.kri.common.file;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public final class FileUtil { public final class FileUtil {
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]"); private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]");
/** /**
@@ -26,7 +27,9 @@ public final class FileUtil {
} }
public static String getExtension(String fileName) { public static String getExtension(String fileName) {
if (fileName == null) return ""; if (fileName == null) {
return "";
}
int dot = fileName.lastIndexOf('.'); int dot = fileName.lastIndexOf('.');
if (dot < 0 || dot == fileName.length() - 1) { if (dot < 0 || dot == fileName.length() - 1) {
return ""; return "";
@@ -35,7 +38,9 @@ public final class FileUtil {
} }
public static String extractFileNameFromPath(String pathLike) { public static String extractFileNameFromPath(String pathLike) {
if (pathLike == null || pathLike.isBlank()) return ""; if (pathLike == null || pathLike.isBlank()) {
return "";
}
String s = pathLike; String s = pathLike;
int q = s.indexOf('?'); int q = s.indexOf('?');
if (q >= 0) { if (q >= 0) {

View File

@@ -9,10 +9,8 @@ import java.time.Duration;
import java.util.Map; import java.util.Map;
/** /**
* 간단한 외부 API 통신 모듈. * 간단한 외부 API 통신 모듈. - url, 추가 헤더, body를 받아 호출합니다. - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다. -
* - url, 추가 헤더, body를 받아 호출합니다. * body는 문자열(JSON 등) 기준입니다.
* - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다.
* - body는 문자열(JSON 등) 기준입니다.
*/ */
public class ExternalApiClient { public class ExternalApiClient {
@@ -36,6 +34,17 @@ public class ExternalApiClient {
this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout; this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout;
} }
private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) {
// GET/DELETE 등 body 없는 메서드는 noBody 사용
if (body == null || body.isEmpty()) {
return switch (method) {
case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString("");
default -> HttpRequest.BodyPublishers.noBody();
};
}
return HttpRequest.BodyPublishers.ofString(body);
}
public ExternalApiResponse get(String url, Map<String, String> headers) { public ExternalApiResponse get(String url, Map<String, String> headers) {
return send("GET", url, headers, null); return send("GET", url, headers, null);
} }
@@ -56,7 +65,8 @@ public class ExternalApiClient {
return send("PATCH", url, headers, body); return send("PATCH", url, headers, body);
} }
private ExternalApiResponse send(String method, String url, Map<String, String> headers, String body) { private ExternalApiResponse send(String method, String url, Map<String, String> headers,
String body) {
try { try {
HttpRequest.Builder builder = HttpRequest.newBuilder() HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(url)) .uri(URI.create(url))
@@ -66,7 +76,9 @@ public class ExternalApiClient {
// 추가 헤더 설정 // 추가 헤더 설정
if (headers != null) { if (headers != null) {
headers.forEach((k, v) -> { headers.forEach((k, v) -> {
if (k != null && v != null) builder.header(k, v); if (k != null && v != null) {
builder.header(k, v);
}
}); });
} }
@@ -81,19 +93,10 @@ public class ExternalApiClient {
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body()); return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
} catch (IOException | InterruptedException e) { } catch (IOException | InterruptedException e) {
// 인터럽트 복원 // 인터럽트 복원
if (e instanceof InterruptedException) Thread.currentThread().interrupt(); if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw new RuntimeException("External API 호출 중 오류가 발생했습니다: " + e.getMessage(), e); throw new RuntimeException("External API 호출 중 오류가 발생했습니다: " + e.getMessage(), e);
} }
} }
private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) {
// GET/DELETE 등 body 없는 메서드는 noBody 사용
if (body == null || body.isEmpty()) {
return switch (method) {
case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString("");
default -> HttpRequest.BodyPublishers.noBody();
};
}
return HttpRequest.BodyPublishers.ofString(body);
}
} }

View File

@@ -8,6 +8,7 @@ import java.util.Map;
* 외부 API 호출 결과를 단순하게 담는 DTO. * 외부 API 호출 결과를 단순하게 담는 DTO.
*/ */
public class ExternalApiResponse { public class ExternalApiResponse {
private final int statusCode; private final int statusCode;
private final Map<String, List<String>> headers; private final Map<String, List<String>> headers;
private final String body; private final String body;
@@ -18,6 +19,10 @@ public class ExternalApiResponse {
this.body = body; this.body = body;
} }
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
return new ExternalApiResponse(status, headers.map(), body);
}
public int getStatusCode() { public int getStatusCode() {
return statusCode; return statusCode;
} }
@@ -29,8 +34,4 @@ public class ExternalApiResponse {
public String getBody() { public String getBody() {
return body; return body;
} }
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
return new ExternalApiResponse(status, headers.map(), body);
}
} }

View File

@@ -2,23 +2,10 @@ package com.kri.common.jpa;
import jakarta.persistence.MappedSuperclass; import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.PrePersist; import jakarta.persistence.PrePersist;
import java.util.UUID; import java.util.UUID;
@MappedSuperclass @MappedSuperclass
public abstract class BaseUuidEntity { public abstract class BaseUuidEntity {
protected abstract String getId();
protected abstract void setId(String id);
/** 엔티티마다 컬럼 길이에 맞춰 오버라이드 */
protected int idLength() { return 32; }
@PrePersist
protected void prePersistId() {
if (getId() == null || getId().isBlank()) {
setId(generateId(idLength()));
}
}
private static String generateId(int length) { private static String generateId(int length) {
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
@@ -34,4 +21,22 @@ public abstract class BaseUuidEntity {
} }
return sb.substring(0, length); return sb.substring(0, length);
} }
protected abstract String getId();
protected abstract void setId(String id);
/**
* 엔티티마다 컬럼 길이에 맞춰 오버라이드
*/
protected int idLength() {
return 32;
}
@PrePersist
protected void prePersistId() {
if (getId() == null || getId().isBlank()) {
setId(generateId(idLength()));
}
}
} }

View File

@@ -3,7 +3,6 @@ package com.kri.common.json;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
@@ -15,9 +14,8 @@ public final class JsonUtil {
} }
/** /**
* 임의의 자바 객체를 Map으로 변환한다. * 임의의 자바 객체를 Map으로 변환한다. 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는
* 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, * 용도이다.
* 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는 용도이다.
*/ */
public static <T> Map<String, Object> toMap(ObjectMapper objectMapper, T source) { public static <T> Map<String, Object> toMap(ObjectMapper objectMapper, T source) {
if (source == null) { if (source == null) {
@@ -38,7 +36,8 @@ public final class JsonUtil {
return Collections.emptyMap(); return Collections.emptyMap();
} }
try { try {
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {}); return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
} catch (IOException e) { } catch (IOException e) {
throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e); throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e);
} }
@@ -68,8 +67,7 @@ public final class JsonUtil {
} }
/** /**
* JSON 문자열을 주어진 타입으로 역직렬화한다. * JSON 문자열을 주어진 타입으로 역직렬화한다. ex) fromJson(mapper, json, UserInfoDto.class)
* ex) fromJson(mapper, json, UserInfoDto.class)
*/ */
public static <T> T fromJson(ObjectMapper objectMapper, String json, Class<T> type) { public static <T> T fromJson(ObjectMapper objectMapper, String json, Class<T> type) {
if (json == null || json.isBlank()) { if (json == null || json.isBlank()) {
@@ -78,13 +76,14 @@ public final class JsonUtil {
try { try {
return objectMapper.readValue(json, type); return objectMapper.readValue(json, type);
} catch (IOException e) { } catch (IOException e) {
throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.", e); throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.",
e);
} }
} }
/** /**
* JSON 문자열을 제네릭 타입으로 역직렬화한다. * JSON 문자열을 제네릭 타입으로 역직렬화한다. ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>()
* ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>() {}) * {})
*/ */
public static <T> T fromJson(ObjectMapper objectMapper, String json, TypeReference<T> typeRef) { public static <T> T fromJson(ObjectMapper objectMapper, String json, TypeReference<T> typeRef) {
if (json == null || json.isBlank()) { if (json == null || json.isBlank()) {
@@ -98,9 +97,8 @@ public final class JsonUtil {
} }
/** /**
* JSON 기반 deep copy (또는 타입 변환). * JSON 기반 deep copy (또는 타입 변환). 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다.
* 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다. * <p>
*
* ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class); * ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class);
*/ */
public static <T> T deepCopy(ObjectMapper objectMapper, T source, Class<T> targetType) { public static <T> T deepCopy(ObjectMapper objectMapper, T source, Class<T> targetType) {
@@ -112,7 +110,7 @@ public final class JsonUtil {
/** /**
* 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용. * 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용.
* * <p>
* ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class); * ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class);
*/ */
public static <S, T> T convert(ObjectMapper objectMapper, S source, Class<T> targetType) { public static <S, T> T convert(ObjectMapper objectMapper, S source, Class<T> targetType) {

View File

@@ -1,10 +1,14 @@
package com.kri.common.redis; package com.kri.common.redis;
import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.*; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
@AutoConfiguration @AutoConfiguration
@ConditionalOnClass(RedisTemplate.class) @ConditionalOnClass(RedisTemplate.class)
@@ -12,11 +16,16 @@ import org.springframework.data.redis.core.*;
@ConditionalOnBean(RedisConnectionFactory.class) @ConditionalOnBean(RedisConnectionFactory.class)
public class CommonRedisAutoConfiguration { public class CommonRedisAutoConfiguration {
@Bean @ConditionalOnMissingBean @Bean
public StringRedisTemplate stringRedisTemplate(org.springframework.data.redis.connection.RedisConnectionFactory cf) { @ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(
org.springframework.data.redis.connection.RedisConnectionFactory cf) {
return new StringRedisTemplate(cf); return new StringRedisTemplate(cf);
} }
@Bean @ConditionalOnMissingBean @Bean
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { return new RedisQueueHelper(rt); } @ConditionalOnMissingBean
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) {
return new RedisQueueHelper(rt);
}
} }

View File

@@ -1,11 +1,21 @@
package com.kri.common.redis; package com.kri.common.redis;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.time.Duration; import java.time.Duration;
import org.springframework.data.redis.core.StringRedisTemplate;
public class RedisQueueHelper { public class RedisQueueHelper {
private final StringRedisTemplate rt; private final StringRedisTemplate rt;
public RedisQueueHelper(StringRedisTemplate rt) { this.rt = rt; }
public void enqueue(String key, String value) { rt.opsForList().rightPush(key, value); } public RedisQueueHelper(StringRedisTemplate rt) {
public String blockingDequeue(String key, Duration timeout) { return rt.opsForList().leftPop(key, timeout); } this.rt = rt;
}
public void enqueue(String key, String value) {
rt.opsForList().rightPush(key, value);
}
public String blockingDequeue(String key, Duration timeout) {
return rt.opsForList().leftPop(key, timeout);
}
} }

View File

@@ -7,4 +7,6 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@AutoConfiguration @AutoConfiguration
@EnableScheduling @EnableScheduling
@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false) @ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false)
public class CommonSchedulingAutoConfiguration { } public class CommonSchedulingAutoConfiguration {
}

View File

@@ -6,13 +6,12 @@ import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@RequiredArgsConstructor @RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter { public class JwtAuthenticationFilter extends OncePerRequestFilter {

View File

@@ -1,8 +1,6 @@
package com.kri.common.security; package com.kri.common.security;
import com.kri.common.auth.apikey.ApiKeyAuthFilter; import com.kri.common.auth.apikey.ApiKeyAuthFilter;
import com.kri.common.auth.apikey.ApiKeyProperties;
import com.kri.common.auth.apikey.ApiKeyUserClaimsProvider;
import com.kri.common.auth.jwt.JwtProperties; import com.kri.common.auth.jwt.JwtProperties;
import com.kri.common.auth.jwt.JwtService; import com.kri.common.auth.jwt.JwtService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -15,10 +13,10 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer; import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@AutoConfiguration(before = SecurityAutoConfiguration.class) @AutoConfiguration(before = SecurityAutoConfiguration.class)
@@ -47,8 +45,7 @@ public class KriSecurityAutoConfiguration {
} }
/** /**
* 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 * 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 이 기본 Security 구성이 적용된다.
* 이 기본 Security 구성이 적용된다.
*/ */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Bean @Bean
@@ -68,8 +65,10 @@ public class KriSecurityAutoConfiguration {
) )
.authorizeHttpRequests(auth -> { .authorizeHttpRequests(auth -> {
// ✅ yaml에서 정의한 public-paths 전부 permitAll // ✅ yaml에서 정의한 public-paths 전부 permitAll
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths().isEmpty()) { if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths()
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new)).permitAll(); .isEmpty()) {
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
.permitAll();
} }
// ✅ 나머지는 전부 인증 필요 // ✅ 나머지는 전부 인증 필요
auth.anyRequest().authenticated(); auth.anyRequest().authenticated();

View File

@@ -1,11 +1,10 @@
package com.kri.common.security; package com.kri.common.security;
import java.util.List;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
@Getter @Getter
@Setter @Setter
@ConfigurationProperties(prefix = "kri.security") @ConfigurationProperties(prefix = "kri.security")
@@ -17,8 +16,7 @@ public class KriSecurityProperties {
private boolean enabled = true; private boolean enabled = true;
/** /**
* 인증 없이 허용할 URL 패턴들 * 인증 없이 허용할 URL 패턴들 서비스에서 application.yml로 오버라이드
* 서비스에서 application.yml로 오버라이드
*/ */
private List<String> publicPaths = List.of( private List<String> publicPaths = List.of(
"/v3/api-docs/**", "/v3/api-docs/**",

View File

@@ -9,10 +9,14 @@ public final class CommonUtil {
} }
public static boolean isNumeric(String s) { public static boolean isNumeric(String s) {
if (s == null || s.isBlank()) return false; if (s == null || s.isBlank()) {
return false;
}
for (int i = 0; i < s.length(); i++) { for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i); char c = s.charAt(i);
if (c < '0' || c > '9') return false; if (c < '0' || c > '9') {
return false;
}
} }
return true; return true;
} }

View File

@@ -1,17 +1,16 @@
package com.kri.common.web; package com.kri.common.web;
import org.springframework.http.HttpStatus;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.springframework.http.HttpStatus;
public class BusinessException extends RuntimeException { public class BusinessException extends RuntimeException {
private final HttpStatus status; private final HttpStatus status;
private final String code; private final String code;
private final Map<String, Object> extras; private final Map<String, Object> extras;
private static String defaultCode(HttpStatus status) { return status.name(); } // 예: NOT_FOUND, CONFLICT …
private BusinessException(HttpStatus status, String code, String message, private BusinessException(HttpStatus status, String code, String message,
Map<String, Object> extras, Throwable cause) { Map<String, Object> extras, Throwable cause) {
super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause); super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause);
@@ -21,10 +20,16 @@ public class BusinessException extends RuntimeException {
: Collections.unmodifiableMap(new HashMap<>(extras)); : Collections.unmodifiableMap(new HashMap<>(extras));
} }
private static String defaultCode(HttpStatus status) {
return status.name();
} // 예: NOT_FOUND, CONFLICT …
public static BusinessException of(HttpStatus status, String code, String message) { public static BusinessException of(HttpStatus status, String code, String message) {
return new BusinessException(status, code, message, null, null); return new BusinessException(status, code, message, null, null);
} }
public static BusinessException of(HttpStatus status, String code, String message, Map<String,Object> extras) {
public static BusinessException of(HttpStatus status, String code, String message,
Map<String, Object> extras) {
return new BusinessException(status, code, message, extras, null); return new BusinessException(status, code, message, extras, null);
} }
@@ -92,11 +97,21 @@ public class BusinessException extends RuntimeException {
return internalError("INTERNAL_SERVER_ERROR", message); return internalError("INTERNAL_SERVER_ERROR", message);
} }
public HttpStatus getStatus() { return status; } public HttpStatus getStatus() {
public String getCode() { return code; } return status;
public Map<String, Object> getExtras() { return extras; } }
/** 편의: 체이닝으로 extras 추가 */ public String getCode() {
return code;
}
public Map<String, Object> getExtras() {
return extras;
}
/**
* 편의: 체이닝으로 extras 추가
*/
public BusinessException with(String key, Object value) { public BusinessException with(String key, Object value) {
var map = new HashMap<>(this.extras); var map = new HashMap<>(this.extras);
map.put(key, value); map.put(key, value);

View File

@@ -2,15 +2,21 @@ package com.kri.common.web;
import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
@AutoConfiguration @AutoConfiguration
@ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true)
public class CommonWebAutoConfiguration { public class CommonWebAutoConfiguration {
@Bean public ErrorAdvice errorAdvice() { return new ErrorAdvice(); }
@Bean public FilterRegistrationBean<TraceFilter> traceFilter() { @Bean
public ErrorAdvice errorAdvice() {
return new ErrorAdvice();
}
@Bean
public FilterRegistrationBean<TraceFilter> traceFilter() {
var reg = new FilterRegistrationBean<>(new TraceFilter()); var reg = new FilterRegistrationBean<>(new TraceFilter());
reg.setOrder(Ordered.HIGHEST_PRECEDENCE); reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
return reg; return reg;

View File

@@ -2,6 +2,11 @@ package com.kri.common.web;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.slf4j.MDC; import org.slf4j.MDC;
@@ -11,6 +16,8 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail; import org.springframework.http.ProblemDetail;
import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.ErrorResponseException; import org.springframework.web.ErrorResponseException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
@@ -18,16 +25,11 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.NoHandlerFoundException; import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.servlet.resource.NoResourceFoundException; import org.springframework.web.servlet.resource.NoResourceFoundException;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
@RestControllerAdvice @RestControllerAdvice
public class ErrorAdvice { public class ErrorAdvice {
private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class); private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class);
// 기본값은 모두 false → 외부 응답엔 노출 안 함 // 기본값은 모두 false → 외부 응답엔 노출 안 함
@@ -36,6 +38,21 @@ public class ErrorAdvice {
@Value("${common.error.expose.service:false}") @Value("${common.error.expose.service:false}")
private boolean exposeService; private boolean exposeService;
private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) {
Set<HttpMethod> httpMethods = e.getSupportedHttpMethods();
if (httpMethods != null && !httpMethods.isEmpty()) {
// ✅ 핵심 수정: Enum::name 대신 HttpMethod::name
return httpMethods.stream()
.map(HttpMethod::name)
.collect(Collectors.joining(", "));
}
String[] methods = e.getSupportedMethods(); // 구버전 호환용
if (methods != null && methods.length > 0) {
return String.join(", ", methods);
}
return "N/A";
}
/* ---------- 공통 ProblemDetail 빌더 ---------- */ /* ---------- 공통 ProblemDetail 빌더 ---------- */
protected ProblemDetail pd(HttpStatus status, String code, String message, protected ProblemDetail pd(HttpStatus status, String code, String message,
HttpServletRequest req, Map<String, Object> extras) { HttpServletRequest req, Map<String, Object> extras) {
@@ -46,19 +63,27 @@ public class ErrorAdvice {
p.setProperty("path", req.getRequestURI()); p.setProperty("path", req.getRequestURI());
String traceId = MDC.get("traceId"); String traceId = MDC.get("traceId");
if (traceId != null) p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적 if (traceId != null) {
p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적
}
// ↓↓↓ 외부로 숨기고 싶으면 기본 false // ↓↓↓ 외부로 숨기고 싶으면 기본 false
if (exposeHandler) { if (exposeHandler) {
String handler = MDC.get("handler"); // Controller#method String handler = MDC.get("handler"); // Controller#method
if (handler != null) p.setProperty("handler", handler); if (handler != null) {
p.setProperty("handler", handler);
}
} }
if (exposeService) { if (exposeService) {
String service = MDC.get("service"); // Service#method (최초 진입) String service = MDC.get("service"); // Service#method (최초 진입)
if (service != null) p.setProperty("service", service); if (service != null) {
p.setProperty("service", service);
}
} }
if (extras != null) extras.forEach(p::setProperty); if (extras != null) {
extras.forEach(p::setProperty);
}
return p; return p;
} }
@@ -100,7 +125,8 @@ public class ErrorAdvice {
/* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */ /* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */
@ExceptionHandler(MethodArgumentNotValidException.class) @ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpServletRequest req) { public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e,
HttpServletRequest req) {
var fieldErrors = e.getBindingResult().getFieldErrors().stream() var fieldErrors = e.getBindingResult().getFieldErrors().stream()
.map(fe -> Map.of( .map(fe -> Map.of(
"field", fe.getField(), "field", fe.getField(),
@@ -125,15 +151,18 @@ public class ErrorAdvice {
} }
@ExceptionHandler(MethodArgumentTypeMismatchException.class) @ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e, HttpServletRequest req) { public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e,
String need = (e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type"; HttpServletRequest req) {
String need =
(e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type";
String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need; String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need;
return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null); return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null);
} }
/* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */ /* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */
@ExceptionHandler(ConstraintViolationException.class) @ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handleConstraintViolation(ConstraintViolationException e, HttpServletRequest req) { public ProblemDetail handleConstraintViolation(ConstraintViolationException e,
HttpServletRequest req) {
var errors = e.getConstraintViolations().stream() var errors = e.getConstraintViolations().stream()
.map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage())) .map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage()))
.collect(Collectors.toList()); .collect(Collectors.toList());
@@ -153,7 +182,8 @@ public class ErrorAdvice {
} }
@ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest req) { public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e,
HttpServletRequest req) {
String supported = resolveSupportedMethods(e); String supported = resolveSupportedMethods(e);
String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported; String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported;
// 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported) // 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported)
@@ -161,14 +191,16 @@ public class ErrorAdvice {
} }
@ExceptionHandler(HttpMediaTypeNotSupportedException.class) @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e, HttpServletRequest req) { public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e,
String supported = e.getSupportedMediaTypes().stream().map(Object::toString).collect(Collectors.joining(",")); HttpServletRequest req) {
String supported = e.getSupportedMediaTypes().stream().map(Object::toString)
.collect(Collectors.joining(","));
String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported; String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported;
return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null); return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null);
} }
/* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */ /* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */
@ExceptionHandler({ ResponseStatusException.class, ErrorResponseException.class }) @ExceptionHandler({ResponseStatusException.class, ErrorResponseException.class})
public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) { public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) {
HttpStatus status; HttpStatus status;
String reason; String reason;
@@ -178,7 +210,8 @@ public class ErrorAdvice {
} else { // ErrorResponseException (Spring 6+) } else { // ErrorResponseException (Spring 6+)
var ere = (ErrorResponseException) e; var ere = (ErrorResponseException) e;
status = HttpStatus.valueOf(ere.getStatusCode().value()); status = HttpStatus.valueOf(ere.getStatusCode().value());
reason = Optional.ofNullable(ere.getBody()).map(ProblemDetail::getDetail).orElse(status.getReasonPhrase()); reason = Optional.ofNullable(ere.getBody()).map(ProblemDetail::getDetail)
.orElse(status.getReasonPhrase());
} }
return pd(status, "ERROR", reason, req, null); return pd(status, "ERROR", reason, req, null);
} }
@@ -189,19 +222,4 @@ public class ErrorAdvice {
log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e); log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e);
return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null); return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null);
} }
private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) {
Set<HttpMethod> httpMethods = e.getSupportedHttpMethods();
if (httpMethods != null && !httpMethods.isEmpty()) {
// ✅ 핵심 수정: Enum::name 대신 HttpMethod::name
return httpMethods.stream()
.map(HttpMethod::name)
.collect(Collectors.joining(", "));
}
String[] methods = e.getSupportedMethods(); // 구버전 호환용
if (methods != null && methods.length > 0) {
return String.join(", ", methods);
}
return "N/A";
}
} }

View File

@@ -1,12 +1,15 @@
package com.kri.common.web; package com.kri.common.web;
import jakarta.servlet.http.*; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC; import org.slf4j.MDC;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class MdcHandlerConfig { public class MdcHandlerConfig {
@Bean @Bean
public WebMvcConfigurer mdcWebMvcConfigurer() { public WebMvcConfigurer mdcWebMvcConfigurer() {
return new WebMvcConfigurer() { return new WebMvcConfigurer() {
@@ -14,7 +17,8 @@ public class MdcHandlerConfig {
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() { registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() {
@Override @Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) { public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
Object handler) {
if (handler instanceof HandlerMethod hm) { if (handler instanceof HandlerMethod hm) {
String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController
String method = hm.getMethod().getName(); // ex) create String method = hm.getMethod().getName(); // ex) create
@@ -22,8 +26,10 @@ public class MdcHandlerConfig {
} }
return true; return true;
} }
@Override @Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) { public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
Object handler, Exception ex) {
MDC.remove("handler"); MDC.remove("handler");
} }
}); });

View File

@@ -1,25 +1,30 @@
package com.kri.common.web; package com.kri.common.web;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*; import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC; import org.slf4j.MDC;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Aspect @Aspect
@Component @Component
public class ServiceMdcAspect { public class ServiceMdcAspect {
@Around("within(@org.springframework.stereotype.Service *)") @Around("within(@org.springframework.stereotype.Service *)")
public Object aroundService(ProceedingJoinPoint pjp) throws Throwable { public Object aroundService(ProceedingJoinPoint pjp) throws Throwable {
boolean first = (MDC.get("service") == null); boolean first = (MDC.get("service") == null);
if (first) { if (first) {
String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService
String mtd = pjp.getSignature().getName(); // ex) enqueue String mtd = pjp.getSignature().getName(); // ex) enqueue
MDC.put("service", cls + "#" + mtd); // ex) ExportService#enqueue MDC.put("service",
cls + "#" + mtd); // ex) ExportService#enqueue
} }
try { try {
return pjp.proceed(); return pjp.proceed();
} finally { } finally {
if (first) MDC.remove("service"); if (first) {
MDC.remove("service");
}
} }
} }
} }

View File

@@ -1,13 +1,18 @@
package com.kri.common.web; package com.kri.common.web;
import jakarta.servlet.*; import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import java.io.IOException; import java.io.IOException;
import java.util.UUID; import java.util.UUID;
import org.slf4j.MDC;
public class TraceFilter implements Filter { public class TraceFilter implements Filter {
private static final String REQ_HEADER = "X-Request-Id"; private static final String REQ_HEADER = "X-Request-Id";
private static final String MDC_KEY = "traceId"; private static final String MDC_KEY = "traceId";
@@ -18,7 +23,9 @@ public class TraceFilter implements Filter {
var httpRes = (HttpServletResponse) res; var httpRes = (HttpServletResponse) res;
String id = httpReq.getHeader(REQ_HEADER); String id = httpReq.getHeader(REQ_HEADER);
if (id == null || id.isBlank()) id = UUID.randomUUID().toString(); if (id == null || id.isBlank()) {
id = UUID.randomUUID().toString();
}
try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) { try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) {
httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo

View File

@@ -12,7 +12,9 @@ public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
} }
private <T extends CodeEnum> T convert(String source, Class<T> targetType) { private <T extends CodeEnum> T convert(String source, Class<T> targetType) {
if (source == null || source.isBlank()) return null; if (source == null || source.isBlank()) {
return null;
}
// 1) enum name으로 먼저 시도 (EMAIL, SMS 등) // 1) enum name으로 먼저 시도 (EMAIL, SMS 등)
if (targetType.isEnum()) { if (targetType.isEnum()) {
@@ -31,6 +33,7 @@ public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
} }
} }
throw new IllegalArgumentException("Unknown enum value: " + source + " for " + targetType.getName()); throw new IllegalArgumentException(
"Unknown enum value: " + source + " for " + targetType.getName());
} }
} }

View File

@@ -1,10 +1,9 @@
package com.kri.common.webmvc; package com.kri.common.webmvc;
import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.security.web.util.matcher.IpAddressMatcher; import org.springframework.security.web.util.matcher.IpAddressMatcher;
import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
public class IpAccessControlService { public class IpAccessControlService {

View File

@@ -1,13 +1,12 @@
package com.kri.common.webmvc; package com.kri.common.webmvc;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter @Getter
@Setter @Setter
@@ -15,8 +14,7 @@ import java.util.stream.Stream;
public class KriIpAccessProperties { public class KriIpAccessProperties {
/** /**
* 공통에서 고정으로 들고 갈 기본 CIDR 들 * 공통에서 고정으로 들고 갈 기본 CIDR 들 → setter 없음 (외부에서 못 바꿈)
* → setter 없음 (외부에서 못 바꿈)
*/ */
private final List<String> defaultCidrs = List.of( private final List<String> defaultCidrs = List.of(
"127.0.0.1/32", // 로컬 IPv4 "127.0.0.1/32", // 로컬 IPv4
@@ -26,9 +24,8 @@ public class KriIpAccessProperties {
); );
/** /**
* 서비스에서 추가로 넣고 싶은 CIDR 목록 * 서비스에서 추가로 넣고 싶은 CIDR 목록 application.yml / properties 로 바인딩되는 리스트
* application.yml / properties 로 바인딩되는 리스트 * <p>
*
* 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16 * 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16
*/ */
private List<String> additionalCidrs = new ArrayList<>(); private List<String> additionalCidrs = new ArrayList<>();

View File

@@ -20,6 +20,8 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class KriWebMvcAutoConfiguration { public class KriWebMvcAutoConfiguration {
private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor) private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor)
// 선택 주입: 있으면 쓰고, 없으면 안 씀
private final ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider;
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@@ -33,9 +35,6 @@ public class KriWebMvcAutoConfiguration {
return new IpAccessControlInterceptor(service); return new IpAccessControlInterceptor(service);
} }
// 선택 주입: 있으면 쓰고, 없으면 안 씀
private final ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider;
@Bean @Bean
@ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작 @ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작
@ConditionalOnMissingBean @ConditionalOnMissingBean
@@ -75,7 +74,8 @@ public class KriWebMvcAutoConfiguration {
} }
@Override @Override
public void addArgumentResolvers(java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) { public void addArgumentResolvers(
java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add); requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add);
} }

View File

@@ -1,7 +1,7 @@
package com.kri.common.webmvc; package com.kri.common.webmvc;
import com.kri.common.auth.jwt.JwtService;
import com.kri.common.auth.dto.JwtUserClaimsDto; import com.kri.common.auth.dto.JwtUserClaimsDto;
import com.kri.common.auth.jwt.JwtService;
import io.jsonwebtoken.JwtException; import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;

View File

@@ -8,6 +8,7 @@ import lombok.Setter;
@Setter @Setter
@Schema(description = "페이지 검색 조건") @Schema(description = "페이지 검색 조건")
public class PageRequestDto { public class PageRequestDto {
@Schema(description = "페이지 번호") @Schema(description = "페이지 번호")
private int pageIndex = 0; // 0-base private int pageIndex = 0; // 0-base
@Schema(description = "페이지 크기") @Schema(description = "페이지 크기")

View File

@@ -1,14 +1,14 @@
package com.kri.common.webmvc.page; package com.kri.common.webmvc.page;
import java.util.List;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import java.util.List;
@Getter @Getter
@Builder @Builder
public class PageResponseDto <T> { public class PageResponseDto<T> {
private List<T> content; private List<T> content;
private long totalElements; private long totalElements;
private int totalPages; private int totalPages;

View File

@@ -1,17 +1,21 @@
package com.kri.common.webmvc.page; package com.kri.common.webmvc.page;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.*;
import java.util.stream.Collectors;
public final class Pageables { public final class Pageables {
private Pageables() {}
private Pageables() {
}
public static Pageable of(PageRequestDto req, Class<?> sortType) { public static Pageable of(PageRequestDto req, Class<?> sortType) {
int page = Math.max(req.getPageIndex(), 0); int page = Math.max(req.getPageIndex(), 0);
@@ -23,7 +27,9 @@ public final class Pageables {
private static Sort buildSort(PageRequestDto req, Class<?> sortType) { private static Sort buildSort(PageRequestDto req, Class<?> sortType) {
String sortBy = req.getSortBy(); String sortBy = req.getSortBy();
if (sortBy == null || sortBy.isBlank()) return null; if (sortBy == null || sortBy.isBlank()) {
return null;
}
Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir()) Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir())
? Sort.Direction.ASC ? Sort.Direction.ASC
@@ -55,8 +61,12 @@ public final class Pageables {
Set<String> props = new HashSet<>(); Set<String> props = new HashSet<>();
for (PropertyDescriptor pd : pds) { for (PropertyDescriptor pd : pds) {
String name = pd.getName(); String name = pd.getName();
if ("class".equals(name)) continue; if ("class".equals(name)) {
if (pd.getReadMethod() == null) continue; continue;
}
if (pd.getReadMethod() == null) {
continue;
}
props.add(name); props.add(name);
} }
return props; return props;

View File

@@ -2,49 +2,49 @@
<configuration scan="true"> <configuration scan="true">
<!-- Spring property 사용 (없으면 기본값) --> <!-- Spring property 사용 (없으면 기본값) -->
<springProperty scope="context" name="APP_NAME" source="app.name" defaultValue="app"/> <appender class="ch.qos.logback.core.ConsoleAppender" name="CONSOLE">
<springProperty scope="context" name="LOG_DIR" source="logging.file.path" defaultValue="logs"/>
<!-- 공통 패턴: traceId/handler/service(MDC) 포함 -->
<property name="LOG_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}] [%X{handler}] [%X{service}] %-5level %logger{36} - %msg%n"/>
<!-- 콘솔 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder> <encoder>
<!-- Spring Boot 확장 패턴도 사용할 수 있음: %clr(%level) 등 --> <!-- Spring Boot 확장 패턴도 사용할 수 있음: %clr(%level) 등 -->
<pattern>${LOG_PATTERN}</pattern> <pattern>${LOG_PATTERN}</pattern>
</encoder> </encoder>
</appender> </appender>
<appender class="ch.qos.logback.core.rolling.RollingFileAppender" name="FILE">
<!-- 롤링 파일 (일 단위) -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_DIR}/${APP_NAME}.log</file>
<encoder> <encoder>
<pattern>${LOG_PATTERN}</pattern> <pattern>${LOG_PATTERN}</pattern>
</encoder> </encoder>
<file>${LOG_DIR}/${APP_NAME}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}.log.gz</fileNamePattern> <fileNamePattern>${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}.log.gz</fileNamePattern>
<maxHistory>14</maxHistory> <!-- 보관 일수 --> <maxHistory>14</maxHistory> <!-- 보관 일수 -->
</rollingPolicy> </rollingPolicy>
</appender> </appender>
<!-- (권장) 비동기 래핑: 파일 I/O를 비동기로 --> <!-- 공통 패턴: traceId/handler/service(MDC) 포함 -->
<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender"> <appender class="ch.qos.logback.classic.AsyncAppender" name="ASYNC_FILE">
<queueSize>8192</queueSize> <appender-ref ref="FILE"/>
<discardingThreshold>0</discardingThreshold> <discardingThreshold>0</discardingThreshold>
<neverBlock>true</neverBlock> <neverBlock>true</neverBlock>
<appender-ref ref="FILE"/> <queueSize>8192</queueSize>
</appender> </appender>
<!-- 콘솔 -->
<property name="LOG_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}] [%X{handler}] [%X{service}] %-5level %logger{36} - %msg%n"/>
<!-- 롤링 파일 (일 단위) -->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ASYNC_FILE"/>
</root>
<!-- (권장) 비동기 래핑: 파일 I/O를 비동기로 -->
<springProperty defaultValue="logs" name="LOG_DIR" scope="context" source="logging.file.path"/>
<!-- 패키지별 레벨(선택) --> <!-- 패키지별 레벨(선택) -->
<!-- <logger name="com.kri" level="INFO" additivity="false"> <!-- <logger name="com.kri" level="INFO" additivity="false">
<appender-ref ref="CONSOLE"/> <appender-ref ref="CONSOLE"/>
<appender-ref ref="ASYNC_FILE"/> <appender-ref ref="ASYNC_FILE"/>
</logger> --> </logger> -->
<root level="INFO"> <springProperty defaultValue="app" name="APP_NAME" scope="context" source="app.name"/>
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ASYNC_FILE"/>
</root>
</configuration> </configuration>