Spring boot에서 Base url을 설정하는 방법

주의

이 문건은 과거 Hexo 블로그 (2019-01-31) 에서 이동된 문서입니다.

시간이 지남에 따라 최신 기술과 다를 수 있으니 주의 바랍니다.



Spring boot에서 특정 url을 베이스로 잡고 싶을 때

최근 프로젝트를 진행하면서 특정 컨트롤러의 url을 기본으로 잡고 싶었다.
말이 뭔가 이상한데 쉽게 예제로 표현을 하자면…

/rest/test/v10/*

위와 같은 샘플 url이 있고 앞의 rest/test 이 부분이 경우에 따라 변경이 되어 매번 컨트롤러에서 수정이 번거로웠다.
그래서 특정 url을 베이스로 잡고 처리하는 방법을 찾아보았다.


How to?

몇 가지 방법이 있는데 이 중 사용하기 편한 두 가지 방법을 알아보겠다.


1. Custom Annotation 사용

이 방법은 커스텀 어노테이션을 하나 만들고 이것을 적용할 컨트롤러에 붙여준다.
먼저 커스텀 어노테이션을 하나 만들어준다.

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@RestController
@RequestMapping("/rest/test/v10/*")
public @interface CustomBaseControllerAnnotation {}

그리고 적용할 컨트롤러에 아래와 같이 붙여서 사용한다.

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

@CustomBaseControllerAnnotation
public class TestOneController {

    @RequestMapping("/users")
    public String firstMethod(){
        return "User List~";
    }
}

이렇게 공통적으로 사용할 컨트롤러에 어노테이션만 붙이고 RequestMapping이나 GetMapping 등의 메서드로 뒤를 알맞게 맞춰주면 된다.


2. Base Controller 상속

1번과 유사한데 커스텀 어노테이션 대신에 공통 컨트롤러를 하나 만들고 이것을 상속받아서 사용하면 된다.

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

@RequestMapping("/rest/test/v10/*")
public class BaseController {}

위와 같이 베이스 컨트롤러를 하나 만들고 아래와 같이 적용해서 사용한다.

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

@RestController
public class TestOneController extends BaseController {

    @RequestMapping("/users")
    public String firstMethod(){
        return "User List~";
    }
}

정리

위에서 사용한 방법 외에 Spring Data Rest를 활용하여 처리하는 방법이 있는데 이는 아래의 참고 StackOverFlow를 참고하자.

참고 항목
Stackoverflow


Written by@MHLab
로또는 흑우집합소 🎲
와인관리, 시음노트, 셀러관리는 마와셀 🥂

🫥 My Service|  📜 Contact|  💻 GitHub