๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐ŸŒฟ Spring/โœ… RESTful Web Service

2. User Service API ๊ตฌํ˜„

by nitronium102 2023. 6. 20.

User ๋„๋ฉ”์ธ ํด๋ž˜์Šค ์ƒ์„ฑ

๋„๋ฉ”์ธ

ํŠน์ • ์ „๋ฌธ ๋ถ„์•ผ์—์„œ ์‚ฌ์šฉ๋˜๋Š” ์ „๋ฌธ ์ง€์‹

์Šคํ…Œ๋ ˆ์˜คํƒ€์ž…

ํ•ด๋‹น ํด๋ž˜์Šค๊ฐ€ ์–ด๋Š ์šฉ๋„๋กœ ์‚ฌ์šฉ๋  ๊ฒƒ์ธ์ง€ ๋‚˜ํƒ€๋‚ด๋Š” ๊ฒƒ → ์˜์กด์„ฑ ์ฃผ์ž…์— ๋„์›€๋œ๋‹ค.

ex) @RestController, @Service

POST

@RequestBody ๋ฅผ ์„ ์–ธํ•ด ํ˜„์žฌ variable์ด requestbody ํ˜•์‹์œผ๋กœ ๋“ค์–ด์˜จ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๋ฆผ

HTTP Status Code

  • 2XX → OK
  • 4XX → Client
  • 5XX → Server

@ServletUriComponentsBuilder๋ฅผ ์ด์šฉํ•ด ํ˜ธ์ถœ ๋ฐฉ๋ฒ•์— ๋”ฐ๋ผ ์ ์ ˆํ•œ status code๋ฅผ ๋ฐ˜ํ™˜ํ•จ

@PostMapping("/users")
	public ResponseEntity<User> createUser(@RequestBody User user){
		User savedUser = service.save(user);

		URI location = ServletUriComponentsBuilder.fromCurrentRequest()
			.path("/{id}")
			.buildAndExpand(savedUser.getId())
			.toUri();

		return ResponseEntity.created(location).build();
	}

Exception Handling

[Controller]
@GetMapping("/users/{id}")
	public User retrieveUser(@PathVariable int id) {
		User user = service.findOne(id);
		if (user == null){
			throw new UserNotFoundException(String.format("ID[%s] is not found", id));
		}
		return user;
	}

[Exception]
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
	public UserNotFoundException(String message) {
		super(message);
	}
}

AOP ์‚ฌ์šฉ(Aspect Oriented Programming)

์Šคํ”„๋ง ๋ถ€ํŠธ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋‚ด์—์„œ ๊ณตํ†ต์ ์œผ๋กœ ์ฒ˜๋ฆฌ๋˜์–ด์•ผ ํ•˜๋Š” ๋กœ์ง์ด๋‚˜ ๋ฉ”์†Œ๋“œ ์ถ”๊ฐ€

Aspect๋กœ ๋ชจ๋“ˆํ™”ํ•˜๊ณ  ํ•ต์‹ฌ์ ์ธ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์—์„œ ๋ถ„๋ฆฌํ•˜์—ฌ ์žฌ์‚ฌ์šฉ

  • @ControllerAdvice
  • ๋ชจ๋“  Controller๊ฐ€ ์‹คํ–‰๋  ๋•Œ annotation์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” bean์ด ํ•ญ์ƒ ๋จผ์ € ์‹คํ–‰๋จ
@ExceptionHandler(UserNotFoundException.class)
	public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request) {
		ExceptionResponse exceptionResponse =
			new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
		return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
	}

๋Œ“๊ธ€