์ด ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ResponseEntity ์๋ต์ ์ผ๊ด๋ ํฌ๋งท์ ์ ๊ณตํ๊ธฐ์ํด ์ ์๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋๋ค. ๐ข
ํด๋น ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ํฌํธ ํ๊ณ ์๋์ ๊ฐ์ด ์ค์ ํด์ฃผ์ ํ ์ฌ์ฉํ ์ ์์ต๋๋ค.
//setting.gradle
//๋ค์ ๊ณผ ๊ฐ์ด public repo์์ ์์ค์ปจํธ๋กค๋ฌ๋ฅผ ์ถ๊ฐํด์ค๋๋ค.
sourceControl {
gitRepository("https://github.com/FeelingXD/common-api-response"){
producesModule("org.feelingxd:common-api-response")
}
}
//build.gradle
//setting.gradle ์ถ๊ฐ ์ดํ build.gradle์์ ์ฝ๋๋ฅผ ์ํฌํธํฉ๋๋ค.
dependencies {
implementation 'org.feelingxd:common-api-response:{version}'
}
ApiResponse์ ํํ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
public class ApiResponse<T> {
private String code;
private HttpStatus status;
private String msg;
private T data; // data๋ ์ต์
์ด๋ฉฐ ์ ํด์ค ๋ฐ์ดํฐ ๊ฐ ์์๊ฒฝ์ฐ ์ฌ์ฉํฉ๋๋ค.
}
{
code: "{CODE_NAME}",
status: "{HTTP_STATUS}",
msg: "{MSG}",
data: "{DATA}"
}
//Code inteface๋ฅผ ๊ตฌํํด์ Custom Code๋ฅผ ๊ตฌํํ ์์์ต๋๋ค.
public enum ExampleErrorCode implements Code {
EXAMPLE_ERROR_CODE(HttpStatus.BAD_REQUEST, "ํ
์คํธ ์๋ฌ์ฝ๋์
๋๋ค. xD");
private final HttpStatus status;
private final String msg;
public HttpStatus getStatus() {
return this.status;
}
public String getMsg() {
return this.msg;
}
private ExampleErrorCode(HttpStatus status, String msg) {
this.status = status;
this.msg = msg;
}
}
//Api response๋ builder ํจํด์ด ์ ์ฉ๋์ด์์ผ๋ฉฐ
// ResponseEntityํ์
์ผ๋ก ๋ณํ๊ฐ๋ฅํ๋๋ก ์ค๊ณ๋์ด์์ต๋๋ค.
// ๋ค์ ์์ ๋ ๊ฐ๋จํ๊ฒ ApiResponse->ResponseEntity๋ก ๋ค์๊ณผ๊ฐ์ด ๋น๋ํ ์์์ต๋๋ค.
public class Example {
public static void main(String[] args){
var responseEntity =ApiResponse.builder()
.code(YourCode.EXAMPLE_ERROR_CODE)
.data(YourCode.code) //optional
.toEntity(); // ResponseEntity class
var apiResponse =ApiResponse.builder()
.code(YourCode.EXAMPLE_ERROR_CODE)
.data(YourCode.code) //optional
.build() // ApiResponse class
}
}
//code Example
@RestController
@RequestMapping("/")
public class testController {
@GetMapping("api")
public ResponseEntity<ApiResponse<String>> commonApiResponse(){
return ApiResponse.builder()
.code(ExampleErrorCode.EXAMPLE_ERROR_CODE)
.toEntity();
}
}
{
code: "EXAMPLE_ERROR_CODE",
status: "400",
msg: "ํ
์คํธ ์๋ฌ์ฝ๋์
๋๋ค. xD",
data: null
}
- Java > 8
- Spring-Web 2.7
- Lombok