@ResponseBody 어노테이션은 스프링 MVC에서 컨트롤러 메서드의 반환값을 HTTP 응답 본문으로 직접 전송할 때 사용하는 어노테이션입니다.
기본적인 사용 방법은 다음과 같습니다:
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
@GetMapping("/users/{id}")
@ResponseBody
public User getUser(@PathVariable Long id) {
// 사용자 조회 로직
return userService.findById(id);
}
}
Content-Type 헤더를 자동으로 설정합니다.클래스 레벨에 적용하여 모든 메서드에 @ResponseBody를 적용할 수 있습니다:
@Controller
@ResponseBody
public class UserApiController {
// 모든 메서드가 @ResponseBody를 사용한 것처럼 동작
}
더 세밀한 제어가 필요한 경우 ResponseEntity를 사용할 수 있습니다:
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.findById(id);
if (user != null) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.notFound().build();
}
}
특별한 형식의 응답을 생성해야 할 경우, 커스텀 HttpMessageConverter를 구현하고 등록할 수 있습니다:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MyCustomMessageConverter());
}
}
@RestController 어노테이션은 @Controller와 @ResponseBody를 결합한 것입니다. @RestController를 사용하면 클래스의 모든 메서드에 자동으로 @ResponseBody가 적용됩니다:
@RestController
public class UserApiController {
// 모든 메서드가 자동으로 @ResponseBody를 사용한 것처럼 동작
}
@ResponseBody를 사용할 때 발생할 수 있는 예외를 처리하려면 @ExceptionHandler를 사용할 수 있습니다:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public ErrorResponse handleException(Exception ex) {
return new ErrorResponse("An error occurred: " + ex.getMessage());
}
}
@ResponseBody가 적용된 컨트롤러 메서드를 테스트할 때:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(1));
}
}
ResponseEntity를 사용하여 적절한 HTTP 상태 코드를 반환하세요.@ResponseBody는 RESTful API 개발에서 매우 유용한 어노테이션입니다. 객체를 HTTP 응답으로 쉽게 변환할 수 있게 해주며, 이를 통해 클라이언트에게 데이터를 효율적으로 전달할 수 있습니다. @RestController와 함께 사용하면 더욱 간결한 코드를 작성할 수 있습니다. 다만, 보안과 성능 측면에서 주의가 필요하며, 적절한 예외 처리와 문서화가 동반되어야 합니다.
@RestController
@Controller
@RequestBody
@ExceptionHandler
@ControllerAdvice