Spring Boot 3 버전에서 Controller를 생성하는 방법에 대해 설명드리겠습니다.
컨트롤러의 역할
Controller는 MVC 패턴에서 Controller 부분을 담당합니다.
MVC(모델 - 뷰 - 컨트롤러) 패턴에 대해 간단하게 설명하면, 모델은 데이터, 뷰는 화면, 컨트롤러는 모델과 뷰를 연결하는 역할을 합니다.
사용자는 컨트롤러를 사용해서 모델(데이터)의 상태를 바꾸고, 컨트롤러는 모델의 바뀐 상태를 뷰에 보내서 사용자가 알 수 있게 합니다.
Controller 생성하기
Spring Boot는 Controller를 생성할 수 있는 어노테이션을 제공하고 있습니다.
예제 프로젝트에는 security 의존성이 포함되어있어서 제외하고 진행하면 됩니다.
그냥 Spring Boot 프로젝트를 생성할 때 spring-boot-starter-web(Spring Web) 의존성만 추가해도 됩니다.
controller 파일 생성
Controller 어노테이션을 사용하려면 Controller 역할을 할 자바 클래스 파일을 생성해야 합니다.

루트 패키지 경로(Demo1Application 파일이 있는 위치)에 생성해도 문제는 없지만, 나중에 프로젝트가 커지면 파일 관리하기 복잡해지니까 패키지를 따로 만들어서 정리해두는 것이 좋습니다.
파일을 생성하고 다음과 같이 코드를 작성합니다.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class DemoController {
@ResponseBody
@GetMapping("/hello")
public String hello() {
return "hello!";
}
}
컨트롤러를 생성하는 방법은 간단합니다.
컨트롤러 역할을 하고자 하는 클래스에 @Controller 어노테이션을 추가하면 스프링 부트 내부에서 컨트롤러로 인식됩니다.
@Controller와 @ResponseBody를 같이 사용하였는데, 예제에 사용된 프로젝트에는 별도의 뷰(화면)가 없기때문에 @Controller를 그대로 사용하면 뷰가 없어서 오류가 발생합니다.

@ResponseBody를 함께 사용하면 응답값을 뷰로 변환하지 않고 응답값을 그대로 반환합니다.

리턴값인 "hello!"를 그대로 반환하였습니다.
@RestController 사용법
@RestController를 사용하면 @Controller와 @ResponseBody를 한번에 쓸 수 있습니다.
@RestController는 RESTful API를 생성할 때 사용됩니다.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoRestController {
@GetMapping("/hello2")
public String hello() {
return "hello!2";
}
}
@Controller 부분을 @RestController로 바꾸고 @ResponseBody를 제거하면 됩니다.
@GetMapping에 사용된 주소가 같으면 실행할 때 오류가 발생하니까 이전에 만든 주소와 겹치지 않게 다른 주소를 사용합니다.

@RestController 내부에는 @Controller와 @ResponseBody가 같이 사용되고 있습니다.

그래서 Controller + ResponseBody를 합친 것과 같은 결과를 반환합니다.
Reference