January 31, 2019
최근 프로젝트를 진행하면서 특정 컨트롤러의 url을 기본으로 잡고 싶었다.
말이 뭔가 이상한데 쉽게 예제로 표현을 하자면…
/rest/test/v10/*
위와 같은 샘플 url이 있고 앞의 rest/test 이 부분이 경우에 따라 변경이 되어 매번 컨트롤러에서 수정이 번거로웠다.
그래서 특정 url을 베이스로 잡고 처리하는 방법을 찾아보았다.
몇 가지 방법이 있는데 이 중 사용하기 편한 두 가지 방법을 알아보겠다.
이 방법은 커스텀 어노테이션을 하나 만들고 이것을 적용할 컨트롤러에 붙여준다.
먼저 커스텀 어노테이션을 하나 만들어준다.
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 등의 메서드로 뒤를 알맞게 맞춰주면 된다.
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