Spring/SpringBoot
Annotation란? @RestController, @GetMapping
hyeonseong
2022. 8. 24. 14:51
Annotation란?
- 사전적 의미로는 "주석" 이라는 의미이다. Spring에서는 클래스, 메서드에 추가해 다양한 기능을 수행 하는 역할을 한다.
- Annotation을 사용하게 되면 코드의 길이, 유지보수, 생산성 측면에서 좋다.
@RestController (@Controller + @ResponseBody)
- 클래스에 @RestController을 적어주면 객체 자체를 반환해준다.
@GetMapping
- HTTP Get 요청을 처리하는 메서드를 맵핑 하는 어노테이션이다.
- 메서드에 따라 페이지의 주소를 결정한다.
위의 2개 말고도 굉장히 많은 어노테이션이 있다. (추후 공부)
예제1
@RestController //DemoController클래스의 컨트롤러
public class DemoController {
@GetMapping("/index")//localhost:8000/index
public String index() {
return "Hello world";
}
}
예제2
@RestController //DemoController클래스의 컨트롤러
public class DemoController {
@GetMapping("/h1") //localhost:8000/h1
public String h1() {
return "<h1>Hello world</h1>";
}
}
예제3
@RestController
public class DemoController {
@GetMapping("/alert")
public String alert() {
return "<script>alert ('Hello world');</script>";
}
}