Spring Boot를 처음 배우면 코드 몇 줄로 브라우저에 글자가 출력됩니다.

처음에는 신기하지만, 곧 이런 생각이 듭니다.

@RestController는 뭐지?
@GetMapping은 왜 쓰지?
클래스와 객체는 무슨 차이지?
생성자는 언제 실행되지?
this는 왜 붙이는 거지?

이번 글에서는 이 개념들을 하나씩 따로 외우지 않고, 브라우저에서 /hello를 실행하는 흐름 안에서 정리해보겠습니다.


1. 먼저 실행 결과부터 보기

우리가 만들 예제의 목표는 간단합니다.

브라우저 주소창에 아래 주소를 입력합니다.

http://localhost:8080/hello

그러면 화면에 아래 문장이 출력됩니다.

Hello, Spring Boot

이 결과를 만들기 위해 Spring Boot Controller를 작성해보겠습니다.


2. 전체 코드

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    private final GreetingService greetingService;

    public HelloController() {
        this.greetingService = new GreetingService("Spring Boot");
    }

    @GetMapping("/hello")
    public String hello() {
        return this.greetingService.makeMessage();
    }
}

class GreetingService {

    private final String name;

    public GreetingService(String name) {
        this.name = name;
    }

    public String makeMessage() {
        return "Hello, " + this.name;
    }
}

처음 보면 코드가 길어 보이지만, 핵심 흐름은 단순합니다.

브라우저에서 /hello 요청
        ↓
HelloController의 hello() 메서드 실행
        ↓
GreetingService 객체의 makeMessage() 실행
        ↓
"Hello, Spring Boot" 반환
        ↓
브라우저에 결과 출력

3. @RestController란?

@RestController
public class HelloController {

}

@RestController는 이 클래스가 웹 요청을 처리하는 Controller라는 뜻입니다.

쉽게 말하면 Spring Boot에게 이렇게 알려주는 표시입니다.

“이 클래스는 브라우저나 클라이언트가 요청을 보내면 응답을 돌려주는 클래스입니다.”

일반 Java 클래스만 만들면 Spring Boot가 자동으로 웹 요청 담당 클래스인지 알 수 없습니다.

그래서 @RestController를 붙여서 이 클래스가 요청을 처리하는 역할임을 알려줍니다.


4. @GetMapping이란?

@GetMapping("/hello")
public String hello() {
    return this.greetingService.makeMessage();
}

@GetMapping("/hello")/hello 주소로 들어온 GET 요청을 이 메서드와 연결합니다.

즉, 브라우저에서 아래 주소로 접속하면

http://localhost:8080/hello

Spring Boot는 hello() 메서드를 실행합니다.

정리하면 다음과 같습니다.

코드의미
@GetMapping("/hello")/hello 주소 요청을 받음
public String hello()요청이 오면 실행되는 메서드
return ...브라우저로 돌려줄 응답

브라우저 주소창에 URL을 입력하는 것도 기본적으로 GET 요청입니다.


5. 클래스와 객체 차이

먼저 클래스부터 보겠습니다.

class GreetingService {

}

클래스는 설계도입니다.

예를 들어 붕어빵 틀이 클래스라면, 실제로 찍혀 나온 붕어빵은 객체입니다.

new GreetingService("Spring Boot")

이 코드는 GreetingService 클래스를 바탕으로 실제 객체를 하나 만드는 코드입니다.

정리하면 다음과 같습니다.

개념설명비유
클래스객체를 만들기 위한 설계도붕어빵 틀
객체클래스로 만든 실제 사용 대상붕어빵

즉, GreetingService는 설계도이고, new GreetingService("Spring Boot")는 실제 객체를 만드는 코드입니다.


6. 생성자 기본 이해하기

생성자는 객체가 만들어질 때 자동으로 실행되는 특별한 메서드입니다.

public GreetingService(String name) {
    this.name = name;
}

이 생성자는 GreetingService 객체가 만들어질 때 실행됩니다.

new GreetingService("Spring Boot")

위 코드가 실행되면 문자열 "Spring Boot"가 생성자의 name으로 들어갑니다.

흐름은 다음과 같습니다.

new GreetingService("Spring Boot")
        ↓
public GreetingService(String name) 실행
        ↓
name에 "Spring Boot" 전달
        ↓
this.name = name 실행
        ↓
객체 안의 name 값이 "Spring Boot"가 됨

생성자는 보통 객체를 만들 때 필요한 초기값을 넣는 용도로 사용합니다.


7. this 키워드란?

private final String name;

public GreetingService(String name) {
    this.name = name;
}

여기서 이름이 같은 name이 두 개 있습니다.

private final String name;

name은 객체가 가지고 있는 변수입니다.

public GreetingService(String name)

name은 생성자로 들어온 값입니다.

둘 다 이름이 name이라서 헷갈릴 수 있습니다.

그래서 this를 붙입니다.

this.name = name;

뜻은 다음과 같습니다.

this.name = 이 객체가 가지고 있는 name
name      = 생성자로 들어온 name

즉, 아래 코드는

this.name = name;

이렇게 해석할 수 있습니다.

생성자로 받은 name 값을
현재 객체의 name 변수에 저장한다.

this는 “현재 객체 자신”을 가리키는 키워드입니다.


8. HelloController의 생성자 보기

이번에는 Controller 안의 생성자를 보겠습니다.

private final GreetingService greetingService;

public HelloController() {
    this.greetingService = new GreetingService("Spring Boot");
}

HelloController 객체가 만들어질 때 생성자가 실행됩니다.

그 안에서 GreetingService 객체를 하나 만듭니다.

new GreetingService("Spring Boot")

그리고 만든 객체를 greetingService 변수에 저장합니다.

this.greetingService = new GreetingService("Spring Boot");

쉽게 말하면 HelloControllerGreetingService를 사용할 수 있도록 준비하는 과정입니다.


9. 브라우저 실행 흐름 다시 보기

이제 전체 흐름을 다시 보면 더 이해하기 쉽습니다.

1. Spring Boot 실행
2. Spring이 HelloController 객체를 생성
3. HelloController 생성자 실행
4. GreetingService 객체 생성
5. 브라우저에서 /hello 접속
6. hello() 메서드 실행
7. greetingService.makeMessage() 실행
8. "Hello, Spring Boot" 문자열 반환
9. 브라우저에 결과 출력

코드로 보면 이 부분이 실행됩니다.

@GetMapping("/hello")
public String hello() {
    return this.greetingService.makeMessage();
}

makeMessage()는 아래 문자열을 만들어 반환합니다.

return "Hello, " + this.name;

그래서 브라우저에는 최종적으로 아래 결과가 보입니다.

Hello, Spring Boot

10. 핵심 용어 정리

용어
JavaSpring Boot를 실행하는 데 많이 사용하는 프로그래밍 언어
Spring Boot웹 서버와 애플리케이션을 쉽게 만들 수 있게 도와주는 Java 프레임워크
클래스객체를 만들기 위한 설계도
객체클래스를 바탕으로 실제 만들어진 사용 대상
생성자객체가 만들어질 때 자동으로 실행되는 코드
this현재 객체 자신을 가리키는 키워드
@RestController이 클래스가 웹 요청을 처리한다는 표시
@GetMapping특정 주소의 GET 요청을 메서드와 연결하는 표시
브라우저사용자가 주소를 입력하고 결과를 확인하는 프로그램

11. 정리

이번 글에서는 Spring Boot에서 브라우저 요청이 Controller로 들어오고, 객체와 생성자를 거쳐 결과가 반환되는 흐름을 살펴봤습니다.

처음에는 @RestController, @GetMapping, 생성자, 객체, this가 각각 따로 노는 개념처럼 보일 수 있습니다.

하지만 실제로는 하나의 흐름 안에서 연결됩니다.

주소 요청 → Controller 실행 → 객체 사용 → 생성자로 값 준비 → this로 현재 객체 값 사용 → 브라우저 응답

Spring Boot를 공부할 때 중요한 것은 어노테이션 이름을 외우는 것보다, 요청이 들어왔을 때 코드가 어떤 순서로 실행되는지 이해하는 것입니다.

이 흐름을 잡으면 Controller, Service, Repository 구조를 배울 때도 훨씬 덜 헷갈립니다.