▣ PART · SPRING

첫 Spring 프로젝트 + Bean 주입

흐름도에 첫 박스를 그린다 — 읽기 자료

📍 지금 어디를 만지고 있나요?
브라우저
Tomcat
Controller + Service Bean
View
DB

1. Part 2 의 도착점

여기까지 우리는 IoC/DI 의 발상, Spring 의 어노테이션, Maven, 환경 구축을 차례로 배웠습니다. 이제 이걸 한 프로젝트로 합쳐봅니다.

2. 프로젝트 생성

Eclipse 메뉴: File → New → Spring Legacy Project → Spring MVC Project. 패키지명은 com.example.demo 같은 점 3 개 형식.

패키지명 규칙

점이 최소 3 개 들어가야 합니다 (예: com.example.demo). 점이 2 개면 마지막이 컨트롤러 패키지가 되어 다른 패키지가 인식 안 되는 함정.

3. Service Bean 작성

package com.example.demo;

import org.springframework.stereotype.Service;

@Service
public class HelloService {
    public String getMessage() {
        return "Spring Bean 으로 인사드립니다!";
    }
}

@Service 한 줄이 이 클래스를 컨테이너의 Bean 으로 등록합니다.

4. Controller — Bean 주입받기

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

    @Autowired
    private HelloService helloService;   // ← 자동 주입

    @RequestMapping("/")
    public String home(Model model) {
        model.addAttribute("msg", helloService.getMessage());
        return "home";
    }
}

new HelloService() 가 없습니다. @Autowired 가 컨테이너에서 알아서 가져옵니다.

5. JSP 화면

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<body>
    <h1>${msg}</h1>
</body>
</html>

${msg} 는 컨트롤러가 모델에 담아준 값. EL(Expression Language) 문법.

6. 실행 결과

스크린샷
크롬에서 localhost:8080/.../ 접속 → "Spring Bean 으로 인사드립니다!" 큰 글씨

7. 일어난 일 정리

① 브라우저 GET / ↓ ② Tomcat 이 요청 받음 ↓ ③ DispatcherServlet → HomeController.home() 호출 ↓ ④ Controller 가 helloService.getMessage() 호출 (Service Bean 은 이미 컨테이너에 만들어져 있고 자동 주입됨) ↓ ⑤ 결과를 model 에 담고 "home" 반환 ↓ ⑥ ViewResolver 가 home → /WEB-INF/views/home.jsp 매핑 ↓ ⑦ JSP 가 ${msg} 채워 HTML 생성 → 응답

8. Before / After

Part 1 끝

Servlet 한 개로 응답.

Part 2 끝

Spring 프로젝트 안에서 Bean 들이 자동 연결되어 응답을 만든다. 다음 Part 에서 MVC 의 본격 분업.