728x90
개념
HandlerMethodArgumentResolver는 Spring MVC에서 컨트롤러 메서드의 매개변수를 해석하고 주입하는 역할을 합니다. 이 인터페이스를 구현하면 사용자 정의 논리로 요청 파라미터를 해석하고 컨트롤러 메서드에 전달할 수 있습니다.
대부분의 API 에서 공통으로 처리하는 로직이 있으면 처리하기 간편하다고 볼 수 있다.
작동 원리
- 요청 수신: 클라이언트가 서버에 요청을 보냅니다.
- 매핑: Spring MVC(Dispatcher Servlet)가 해당 요청을 처리할 핸들러 메서드(컨트롤러 메서드)를 찾습니다.
- 매개변수 해석:
HandlerMethodArgumentResolver구현체가 핸들러 메서드의 매개변수를 해석하고 값을 주입합니다. - 응답 반환: 핸들러 메서드가 실행되고, 결과가 클라이언트에 반환됩니다.
동작 순서
1. Client 가 요청한다(Request).
2. Dispatcher Servlet에서 Request를 처리한다.
3. 요청을 분석하여 Request에 대한 Hadler Mapping을 한다.
- RequestMappingHandlerAdapter(핸들러 매핑에 맞는 어댑터 결정).
- Interceptor 처리
- Argument Resolver 처리 (등록한 리졸버에 대응되는 파라미터 바인딩)
- Message Converter 처리
4. Controller Method invoke
Spring Boot 3.x.x에서의 HandlerMethodArgumentResolver 설정
예제 프로젝트
1. Gradle 설정
build.gradle 파일에 필요한 의존성을 추가합니다.
plugins {
id 'org.springframework.boot' version '3.3.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
2. CustomArgumentResolver 클래스
HandlerMethodArgumentResolver 인터페이스를 구현하여 사용자 정의 매개변수 해석기를 만듭니다.
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
public class CustomArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(CustomType.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, org.springframework.web.bind.support.WebDataBinderFactory binderFactory) throws Exception {
String param = webRequest.getParameter("customParam");
return new CustomType(param);
}
}
3. WebConfig 클래스
WebMvcConfigurer를 사용하여 위에서 구현한 HandlerMethodArgumentResolver를 등록합니다.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new CustomArgumentResolver());
}
}
4. CustomType 클래스
public class CustomType {
private String value;
public CustomType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
5. MyController 클래스
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/custom")
public String handleCustom(CustomType custom) {
return "Received custom parameter: " + custom.getValue();
}
}
요청 예제
서버가 실행된 후, 다음과 같이 요청할 수 있습니다:
GET http://localhost:8080/api/custom?customParam=testValue
응답 예제
{
"message": "Received custom parameter: testValue"
}
결론
HandlerMethodArgumentResolver는 Spring MVC에서 컨트롤러 메서드의 매개변수를 사용자 정의 방식으로 해석하고 주입하는 강력한 도구입니다. 이를 통해 보다 유연하고 확장 가능한 웹 애플리케이션을 개발할 수 있습니다.
'Spring Boot' 카테고리의 다른 글
| [Spring Boot] JWT, JWS, JWE 개념 및 차이점 (0) | 2024.07.08 |
|---|---|
| [Spring Boot] @Value와 @ConfigurationProperties 차이점 (0) | 2024.07.08 |
| [Spring Boot] Spring Boot CORS 설정 (0) | 2024.06.28 |
| [Spring Boot] Spring Boot 에서 Spring REST Docs 설정, Swagger 와 비교 (0) | 2024.06.26 |
| [Spring Boot] JPA QueryDSL 적용 (0) | 2024.06.25 |