@Component
component-scan을 xml에 정의함으로 빈으로 등록될 준비가 된 클래스들을 스캔하고,
@Component Annotation이 있는 클래스에 대하여 bean 인스턴스를 생성한다.
@Component 어노테이션을 구체화 한 @Controller, @Service, @Repository 등이 있다.
명시한 클래스가 Controller/Service/Repository로 사용됨을 Spring Framework에 알린다.
Controller 클래스에 @Controller 어노테이션을 작성하여 해당 클래스가 Controller로 사용된다는것을 알린다.
@Controller
주로 View를 제공하기 위해 사용. @Controller로 지정된 클래스의 메서드는 ViewResolver를 통해
뷰 템플릿을 렌더링하여 클라이언트에 반환함.
@RestController
@Controller + @ResponseBody 이며, 메소드의 return을 JSON 형태로 변환하여 return.
view가 필요없는 API만 지원하는 클래스에 사용되며, json 이나 xml 타입의 return이 목적.
더보기
@Responsebody 어노테이션을 사용하면 http요청 body를 자바 객체로 전달받을 수 있다.
@RestController
public class CommentController {
@Autowired
private CommentService commentService;
@GetMapping("/getCommentList/{postId}")
public List<Comment> getCommentList(@PathVariable("postId") int postId) {
List<Comment> commentList = commentService.getCommentList(postId);
return commentList;
}
}
Mybatis의 selectList를 통해 list컬렉션이 저장된 commentList 변수를 JSON타입으로 변환해 return함.
@Controller와 @RestController 의 차이
@Controller | @RestController |
API와 View 리턴을 동시에 사용하는경우에 사용. API 서비스로 사용하는 경우는 @ResponseBody를 사용하여 객체를 반환 | view 가 필요없는 API 만 지원시 사용. @RestController = @Controller + @ResponseBody |
view 템플릿 return | data(json, xml 등) return |
'Spring framework' 카테고리의 다른 글
[Spring] st_distance_sphere을 사용하여 위치기반 조회 구현 (0) | 2023.12.17 |
---|---|
[Spring] @Value 어노테이션 사용시 Access key cannot be null (1) | 2023.12.02 |
[Spring] Dependency Injection (의존성 주입) 정리 (1) | 2023.10.01 |