Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e2215e2
feat: HTTP 요청/응답 로깅 필터 구현
sukangpunch Dec 31, 2025
609237a
feat: ExceptionHandler에 중복 로깅 방지 플래그 및 userId 로깅 추가
sukangpunch Dec 31, 2025
d265e3b
feat: API 수행시간 로깅 인터셉터 추가
sukangpunch Dec 31, 2025
1653e7c
feat: ApiPerf 인터셉터, Logging 필터 빈 등록
sukangpunch Jan 1, 2026
a087a42
refactor: logback 설정 변경
sukangpunch Jan 1, 2026
0c53761
feat: 쿼리 별 수행시간 메트릭 모니터링 추가
sukangpunch Jan 1, 2026
d83f7d4
refactor: 비효율적인 Time 빌더 생성 개선
sukangpunch Jan 1, 2026
ba07514
feat: 로깅을 위해 HttpServeletRequest 속성에 userId 추가
sukangpunch Jan 1, 2026
e057d2f
refactor: logback 설정 중 local은 console만 찍도록 수정
sukangpunch Jan 1, 2026
239be9d
refactor: FILE_PATTERN -> LOG_PATTERN 으로 수정
sukangpunch Jan 1, 2026
d85041b
test: TokenAuthenticationFilter에서 request에 userId 설정 검증 추가
sukangpunch Jan 2, 2026
42469af
refacotr: 코드 래빗 리뷰사항 반영
sukangpunch Jan 2, 2026
7cb4aab
refactor: 리뷰 내용 반영
sukangpunch Jan 3, 2026
3bf7425
refactor: 로깅 시 민감한 쿼리 파라미터 마스킹
sukangpunch Jan 6, 2026
7857645
refactor: CustomExceptionHandler 원상복구
sukangpunch Jan 6, 2026
3800a98
refactor: 리뷰 사항 반영
sukangpunch Jan 6, 2026
545917a
fix: decode를 두 번 하는 문제 수정
sukangpunch Jan 8, 2026
5af37c3
test: 로깅 관련 filter, interceptor 테스트 추가
sukangpunch Jan 8, 2026
18c6a36
refactor: 코드래빗 리뷰사항 반영
sukangpunch Jan 9, 2026
0ca2f74
refactor: 단위테스트에 TestContainer 어노테이션 제거
sukangpunch Jan 11, 2026
9a77887
fix: conflict 해결
sukangpunch Jan 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ dependencies {
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'com.amazonaws:aws-java-sdk-s3:1.12.782'
implementation 'org.springframework.boot:spring-boot-starter-websocket'

// Database Proxy
implementation 'net.ttddyy.observation:datasource-micrometer:1.2.0'
Comment on lines +72 to +73
Copy link
Copy Markdown

@coderabbitai coderabbitai bot Jan 1, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🌐 Web query:

datasource-proxy net.ttddyy latest version Maven Central 2025

💡 Result:

Latest Maven Central version: 1.11.0 (released July 14, 2025).

Maven dependency:

net.ttddyy
datasource-proxy
1.11.0

Sources: [Maven Repository (1.11.0)] [1], [javadoc.io (1.11.0)] [2], [Maven Central index/metadata] [3].

References

  1. https://mvnrepository.com/artifact/net.ttddyy/datasource-proxy/1.11.0
  2. https://javadoc.io/doc/net.ttddyy/datasource-proxy/1.11.0
  3. https://maven-eu.nuxeo.org/nexus/content/groups/public/net/ttddyy/datasource-proxy/

🌐 Web query:

datasource-micrometer net.ttddyy.observation latest version Maven Central 2025

💡 Result:

The latest Maven Central version is net.ttddyy.observation:datasource-micrometer: 2.0.1. [1][2]

Sources:

  • mvnrepository entry for datasource-micrometer 2.0.1. [1]
  • Official docs (installation snippet showing version 2.0.1). [2]

🌐 Web query:

datasource-proxy 1.11.0 security vulnerability CVE

💡 Result:

I found no public CVE that specifically affects the net.ttddyy datasource‑proxy 1.11.0 library itself. Maven listings for datasource‑proxy 1.11.0 show reported vulnerabilities coming from its dependencies (examples listed there include CVE-2025-68161, CVE-2024-38819, CVE-2023-6378), not a direct CVE for datasource‑proxy. [1]

Note: There is a separate, unrelated Grafana "datasource proxy" advisory (CVE-2025-3454) that affects Grafana’s server API — not the net.ttddyy datasource‑proxy Java library. Do not confuse the two. [2]

Sources:

  • Maven / mvnrepository entry for net.ttddyy:datasource-proxy 1.11.0 (vulnerability list). [1]
  • Grafana security advisory (CVE-2025-3454) — unrelated Grafana product issue. [2]

References:
[1] https://mvnrepository.com/artifact/net.ttddyy/datasource-proxy/1.11.0
[2] https://grafana.com/security/security-advisories/cve-2025-3454/


🌐 Web query:

datasource-micrometer 1.2.0 security vulnerability CVE

💡 Result:

I found no public CVE specifically affecting net.ttddyy.observation:datasource-micrometer version 1.2.0. The Maven listing for that artifact/version shows no CVE entry for the artifact itself. [1]

There are unrelated CVEs for other metric libraries (for example CVE-2020-1960 affecting Apache Flink's JMX reporter), but those do not apply to datasource-micrometer. [2][3]

If you want, I can:

  • scan OSS advisories (GitHub Security Advisories, NVD) for any recent updates, or
  • check your SBOM/dependency tree for transitive vulnerabilities that might affect your build. Which would you prefer?

Sources:
[1] mvnrepository — net.ttddyy.observation:datasource-micrometer 1.2.0.
[2] Micrometer security policy / advisories.
[3] NVD / GitLab advisory — CVE-2020-1960 (example of an unrelated metrics CVE).


데이터소스 프록시 의존성이 추가되었습니다. datasource-micrometer 버전 업그레이드를 권장합니다.

변경 내용:

  1. datasource-proxy:1.11.0 - 최신 버전이며, 쿼리 인터셉션을 위한 핵심 프록시 라이브러리입니다.
  2. datasource-micrometer:1.2.0 - 최신 버전은 2.0.1이므로 업그레이드를 고려하세요. Micrometer와의 통합을 위한 라이브러리입니다.

DataSourceProxyConfig 및 QueryMetricsListener와 연동되어 쿼리별 메트릭 수집을 지원합니다. 현재 datasource-micrometer는 1.2.0 사용 중이지만, 2.0.1이 최신 버전으로 이용 가능합니다. 특정 보안 취약점은 발견되지 않았으나, 최신 버전으로 업그레이드하면 개선 사항과 안정성을 함께 얻을 수 있습니다.

🤖 Prompt for AI Agents
In build.gradle around lines 72 to 74, the datasource-micrometer dependency is
pinned to 1.2.0 but should be upgraded to the current 2.0.1; update the
implementation coordinate from
'net.ttddyy.observation:datasource-micrometer:1.2.0' to
'net.ttddyy.observation:datasource-micrometer:2.0.1' and then run a quick build
and tests to verify compatibility (adjust any import or API usages in
DataSourceProxyConfig/QueryMetricsListener if the newer API changed).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

datasource-micrometer 의존성이 내부적으로 datasource-proxy 를 포함하기에, datasource-proxy 의존성은 제거해도 될 듯 합니다.

버전은 1.2.x 그대로 사용하면 될 듯 합니다. 메이저 버전이 1인 경우 마이너 버전 2가 최신이고, 저희 Spring Boot 버전과 호환됩니다. 메이저 버전 2는 Spring Boot 4.x에서 지원하네요. [참고1], [참고2]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@whqtker 정확한 지적 감사합니다! 제 분석이 잘못되었네요.

말씀하신 내용 정리:

  1. 중복 의존성 제거 필요

    • datasource-micrometer가 내부적으로 datasource-proxy를 포함하고 있어, Line 72의 implementation 'net.ttddyy:datasource-proxy:1.11.0' 라인은 제거해도 됩니다.
  2. 버전 1.2.0이 적절함

    • 현재 프로젝트가 Spring Boot 3.1.5를 사용 중이므로, datasource-micrometer:1.2.0이 올바른 버전입니다.
    • 2.x 버전은 Spring Boot 4.x용이므로 업그레이드하면 안 됩니다.

참고 자료 제공해주셔서 이해가 명확해졌습니다. 중복 의존성을 제거하면 의존성 관리가 더 깔끔해질 것 같습니다!


✏️ Learnings added
Learnt from: whqtker
Repo: solid-connection/solid-connect-server PR: 602
File: build.gradle:72-74
Timestamp: 2026-01-02T08:56:21.107Z
Learning: In the solid-connect-server project using Spring Boot 3.1.5, datasource-micrometer 1.2.x is the correct version. Version 2.x is for Spring Boot 4.x and should not be used with Spring Boot 3.x.

Learnt from: whqtker
Repo: solid-connection/solid-connect-server PR: 602
File: build.gradle:72-74
Timestamp: 2026-01-02T08:56:21.107Z
Learning: The datasource-micrometer dependency (net.ttddyy.observation:datasource-micrometer) internally includes datasource-proxy as a transitive dependency, so explicit datasource-proxy dependency is redundant and should be removed to avoid duplication.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

}

tasks.named('test', Test) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.example.solidconnection.common.config.datasource;

import com.example.solidconnection.common.listener.QueryMetricsListener;
import javax.sql.DataSource;
import lombok.RequiredArgsConstructor;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@RequiredArgsConstructor
@Configuration
public class DataSourceProxyConfig {

private final QueryMetricsListener queryMetricsListener;

@Bean
@Primary
public DataSource proxyDataSource(DataSourceProperties props) {
DataSource dataSource = props.initializeDataSourceBuilder().build();

return ProxyDataSourceBuilder
.create(dataSource)
.listener(queryMetricsListener)
.name("main")
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package com.example.solidconnection.common.config.web;

import com.example.solidconnection.common.interceptor.BannedUserInterceptor;
import com.example.solidconnection.common.filter.HttpLoggingFilter;
import com.example.solidconnection.common.interceptor.ApiPerformanceInterceptor;
import com.example.solidconnection.common.interceptor.RequestContextInterceptor;
import com.example.solidconnection.common.resolver.AuthorizedUserResolver;
import com.example.solidconnection.common.resolver.CustomPageableHandlerMethodArgumentResolver;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
Expand All @@ -17,6 +23,9 @@ public class WebMvcConfig implements WebMvcConfigurer {
private final AuthorizedUserResolver authorizedUserResolver;
private final CustomPageableHandlerMethodArgumentResolver customPageableHandlerMethodArgumentResolver;
private final BannedUserInterceptor bannedUserInterceptor;
private final HttpLoggingFilter httpLoggingFilter;
private final ApiPerformanceInterceptor apiPerformanceInterceptor;
private final RequestContextInterceptor requestContextInterceptor;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
Expand All @@ -27,8 +36,24 @@ public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers)
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(apiPerformanceInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/actuator/**");

registry.addInterceptor(requestContextInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/actuator/**");

registry.addInterceptor(bannedUserInterceptor)
.addPathPatterns("/posts/**", "/comments/**", "/chats/**", "/boards/**");
}

@Bean
public FilterRegistrationBean<HttpLoggingFilter> customHttpLoggingFilter() {
FilterRegistrationBean<HttpLoggingFilter> filterBean = new FilterRegistrationBean<>();
filterBean.setFilter(httpLoggingFilter);
filterBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return filterBean;
Comment on lines +52 to +57
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find HttpLoggingFilter class definition and check for annotations
find . -name "HttpLoggingFilter.java" -type f | head -20

Repository: solid-connection/solid-connect-server

Length of output: 161


🏁 Script executed:

#!/bin/bash
# Search for `@Component` or `@WebFilter` annotations in HttpLoggingFilter
rg -n '@Component|@WebFilter' --type java -A 3 | grep -i 'httplogging' -A 3 -B 3

Repository: solid-connection/solid-connect-server

Length of output: 1025


🏁 Script executed:

#!/bin/bash
# Check for all HttpLoggingFilter registrations
rg -n 'HttpLoggingFilter|FilterRegistrationBean.*HttpLoggingFilter' --type java -B 2 -A 5

Repository: solid-connection/solid-connect-server

Length of output: 7246


🏁 Script executed:

#!/bin/bash
# Check WebMvcConfig.java for the relevant code
cat -n src/main/java/com/example/solidconnection/common/config/web/WebMvcConfig.java | head -70

Repository: solid-connection/solid-connect-server

Length of output: 3189


HttpLoggingFilter의 중복 등록 문제를 반드시 수정해야 합니다.

검증 결과, HttpLoggingFilter@Component 어노테이션이 적용되어 있으면서 동시에 FilterRegistrationBean으로도 등록되고 있습니다. 이는 필터가 두 번 등록되어 실행될 수 있는 심각한 문제입니다.

  1. 현재 상태

    • HttpLoggingFilter 클래스: @Component 어노테이션으로 자동 등록됨
    • WebMvcConfig: FilterRegistrationBean으로 명시적 등록됨
    • 결과: 동일한 필터가 이중 실행될 수 있음
  2. 해결 방법

    • HttpLoggingFilter에서 @Component 어노테이션을 제거하거나
    • WebMvcConfigcustomHttpLoggingFilter() 메서드를 제거하고 순서 제어가 필요하면 다른 방식 적용

필터 우선순위를 Ordered.HIGHEST_PRECEDENCE로 제어하려는 의도가 있으므로, @Component를 제거하고 FilterRegistrationBean 방식만 유지하는 것을 권장합니다.

🤖 Prompt for AI Agents
In
`@src/main/java/com/example/solidconnection/common/config/web/WebMvcConfig.java`
around lines 52 - 57, HttpLoggingFilter is being registered twice (as a
`@Component` and via the WebMvcConfig.customHttpLoggingFilter
FilterRegistrationBean), so remove the `@Component` annotation from the
HttpLoggingFilter class and keep the explicit FilterRegistrationBean
registration (customHttpLoggingFilter) with Ordered.HIGHEST_PRECEDENCE to
control ordering; ensure the HttpLoggingFilter bean instance used by
customHttpLoggingFilter is provided only via the registration path (not
component-scanned).

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package com.example.solidconnection.common.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

@Slf4j
@RequiredArgsConstructor
@Component
public class HttpLoggingFilter extends OncePerRequestFilter {

private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
private static final List<String> EXCLUDE_PATTERNS = List.of("/actuator/**");
private static final List<String> EXCLUDE_QUERIES = List.of("token");
private static final String MASK_VALUE = "****";

@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {

// 1) traceId 부여
String traceId = generateTraceId();
MDC.put("traceId", traceId);

boolean excluded = isExcluded(request);

// 2) 로깅 제외 대상이면 그냥 통과 (traceId는 유지: 추후 하위 레이어 로그에도 붙음)
if (excluded) {
try {
filterChain.doFilter(request, response);
} finally {
MDC.clear();
}
return;
}

printRequestUri(request);

try {
filterChain.doFilter(request, response);
printResponse(request, response);
} finally {
MDC.clear();
}
}

private boolean isExcluded(HttpServletRequest req) {
String path = req.getRequestURI();
for (String p : EXCLUDE_PATTERNS) {
if (PATH_MATCHER.match(p, path)) {
return true;
}
}
return false;
}

private String generateTraceId() {
return java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 16);
}

private void printRequestUri(HttpServletRequest request) {
String methodType = request.getMethod();
String uri = buildDecodedRequestUri(request);
log.info("[REQUEST] {} {}", methodType, uri);
}

private void printResponse(
HttpServletRequest request,
HttpServletResponse response
) {
Long userId = (Long) request.getAttribute("userId");
String uri = buildDecodedRequestUri(request);
HttpStatus status = HttpStatus.valueOf(response.getStatus());

log.info("[RESPONSE] {} userId = {}, ({})", uri, userId, status);
}

private String buildDecodedRequestUri(HttpServletRequest request) {
String path = request.getRequestURI();
String query = request.getQueryString();

if(query == null || query.isBlank()){
return path;
}

String decodedQuery = decodeQuery(query);
String maskedQuery = maskSensitiveParams(decodedQuery);

return path + "?" + maskedQuery;
}

private String decodeQuery(String rawQuery) {
if(rawQuery == null || rawQuery.isBlank()){
return rawQuery;
}

try {
return URLDecoder.decode(rawQuery, StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
log.warn("Query 디코딩 실패 parameter: {}, msg: {}", rawQuery, e.getMessage());
return rawQuery;
}
}

private String maskSensitiveParams(String decodedQuery) {
String[] params = decodedQuery.split("&");
StringBuilder maskedQuery = new StringBuilder();

for(int i = 0; i < params.length; i++){
String param = params[i];

if(!param.contains("=")){
maskedQuery.append(param);
}else{
int equalIndex = param.indexOf("=");
String key = param.substring(0, equalIndex);

if(isSensitiveParam(key)){
maskedQuery.append(key).append("=").append(MASK_VALUE);
}else{
maskedQuery.append(param);
}
}

if(i < params.length - 1){
maskedQuery.append("&");
}
}

return maskedQuery.toString();
}

private boolean isSensitiveParam(String paramKey) {
for (String sensitiveParam : EXCLUDE_QUERIES){
if(sensitiveParam.equalsIgnoreCase(paramKey)){
return true;
}
}
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.example.solidconnection.common.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@RequiredArgsConstructor
@Component
public class ApiPerformanceInterceptor implements HandlerInterceptor {
private static final String START_TIME_ATTRIBUTE = "startTime";
private static final String REQUEST_URI_ATTRIBUTE = "requestUri";
private static final int RESPONSE_TIME_THRESHOLD = 3_000;
private static final Logger API_PERF = LoggerFactory.getLogger("API_PERF");

@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler
) throws Exception {

long startTime = System.currentTimeMillis();

request.setAttribute(START_TIME_ATTRIBUTE, startTime);
request.setAttribute(REQUEST_URI_ATTRIBUTE, request.getRequestURI());

return true;
}

@Override
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex
) throws Exception {
Long startTime = (Long) request.getAttribute(START_TIME_ATTRIBUTE);
if(startTime == null) {
return;
}

long responseTime = System.currentTimeMillis() - startTime;

String uri = request.getRequestURI();
String method = request.getMethod();
int status = response.getStatus();

if (responseTime > RESPONSE_TIME_THRESHOLD) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

개인적으론 if-else 구조가 로직을 이해하는 데 더 좋을 거 같습니다 !

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수정하겠습니다!

API_PERF.warn(
"type=API_Performance method_type={} uri={} response_time={} status={}",
method, uri, responseTime, status
);
}
else {
API_PERF.info(
"type=API_Performance method_type={} uri={} response_time={} status={}",
method, uri, responseTime, status
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.solidconnection.common.interceptor;

import lombok.Getter;

@Getter
public class RequestContext {
private final String httpMethod;
private final String bestMatchPath;

public RequestContext(String httpMethod, String bestMatchPath) {
this.httpMethod = httpMethod;
this.bestMatchPath = bestMatchPath;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.example.solidconnection.common.interceptor;

public class RequestContextHolder {
private static final ThreadLocal<RequestContext> CONTEXT = new ThreadLocal<>();

public static void initContext(RequestContext requestContext) {
CONTEXT.remove();
CONTEXT.set(requestContext);
}

public static RequestContext getContext() {
return CONTEXT.get();
}

public static void clear(){
CONTEXT.remove();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.example.solidconnection.common.interceptor;

import static org.springframework.web.servlet.HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class RequestContextInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler
) {
String httpMethod = request.getMethod();
String bestMatchPath = (String) request.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE);

RequestContext context = new RequestContext(httpMethod, bestMatchPath);
RequestContextHolder.initContext(context);
Comment on lines +19 to +23
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

발생 안할 거 같긴한데 여기서 예외 발생하면 clear가 안되니 try-catch로 catch에서 clear를 호출하는 게 안전할까요~?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 내용을 알아보니까 afterCompletion은 내부적으로 finally 블록에서 호출되므로 return true 가 강제 된다면 무조건 호출 된다고 합니다(예외도 같이 afterCommit 으로 넘어가서 실행)
그리고 RequestContextHolder에서 initContext 메서드에서 초기화 할 때 항상 clear를 해줘서 누수가 발생하진 않을 듯 합니다!


return true;
}

@Override
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex
) {
RequestContextHolder.clear();
}
}
Loading
Loading