[spring] RequestMapping 살펴보기 (feat. 특정 MethodMapping과의 차이점)

YJ KIM·2025년 2월 21일
0
post-thumbnail

오랜만에 스프링으로 개발을 하려다보니 잊은 내용이 너무 많아서 차근차근히 정리하려고 한다!


1. @RequestMapping

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @RequestMapping(value = "/test")
    public void test() {
        System.out.println("Test success!");
    }
}

보통 web API를 구성할 때 Spring boot로 구현한다면 이와 같은 형태로 구현하게 된다.

몇 줄밖에 되지 않는 코드를 두 부분으로 나누면,

  1. @Controller 어노테이션을 통해 해당 클래스를 Controller bean으로 등록한다.
  2. @RequestMapping 어노테이션을 통해 RequestMappingHandlerMapping에 각각의 메소드들이 mapping된다.

위와 같은 부분으로 나뉠 수 있다.
RequestMapping 관련해서는 내부 동작이 나름 복잡하지만(매핑하고 등록하고 하는 로직이 있다) 사용하는 입장에서는 매우 간단하다.

이때 RequestMapping 어노테이션을 한 번 봐보면,

간단하게 name, path, method 등을 기재하게 되어있다.
(주석이 너무 많아서 복붙하기 어려웠다 .. 🥺)

여기서 봐야할 부분은 method 부분이다.

	/**
	 * The HTTP request methods to map to, narrowing the primary mapping:
	 * GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
	 * <p><b>Supported at the type level as well as at the method level!</b>
	 * When used at the type level, all method-level mappings inherit this
	 * HTTP method restriction.
	 */
	RequestMethod[] method() default {};

특정 HTTP Method를 정하고 싶다면, method를 정해줘야 한다.
만일 정하지 않으면 모든 method로 다 매핑되게 된다.

    @RequestMapping(value = "/test")
    public void test() {
        System.out.println("Test success!");
    }

위와 같은 상황에서 GET, POST, PUT 등 여러 method를 설정하고 /test로 요청을 보내도 다 200 ok를 받게 된다.

2. @MethodMapping

그럼 @GetMapping과 @PostMapping 등 다른 어노테이션은 뭘까?
하나를 잡고 살펴보자.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {

GetMapping 어노테이션을 살펴보면 확인할 수 있다.

결론적으로, 특정 Method Mapping 어노테이션은,
RequestMapping 어노테이션에 특정 method로 이미 설정이 된 것 뿐이다.

3. 같은 method, path인 경우는?

@RestController
public class TestController {
    @RequestMapping(value = "/test")
    public void test() {
        System.out.println("Test success!");
    }
    
    @RequestMapping(value = "/test")
    public void test2() {
        System.out.println("두번째 테스트");
    }
}

이러한 경우에는 런타임 에러가 발생하게 된다.

to { [/test]}: There is already 'testController' bean method

이미 해당 메소드가 등록했다는 에러가 발생한다.

만일 같은 이름의 다른 method인 경우 각자의 method를 확실히 기재해줘야 된다.

개인적으로 그냥 method는 무조건 기재하는 게 나은 것 같다. 스펙도 확실히 확인할 수 있기도 하고 다른 method로 접근하는 걸 허용하는 거 자체가 별로임. 결론적으로 RequestMapping 말고 특정 method Mapping 어노테이션을 사용하자~! (결론)


이전에 스프링을 사용한 프로젝트를 했을 땐 내가 개발자가 아니라 어떠한 코더 같아서 .. 몰라도 굳이 확인하고 넘어가지 않았는데, 이젠 접근하는 법이나 개발 공부하는 방법이 바뀌어서 시간이 오래 걸리는 것 같다 .. 하지만 모르고 넘어가는 건 싫다~!

profile
모르면 쓰지 말고 쓸 거면 알고 쓰자

0개의 댓글

관련 채용 정보