▣ PART · SPRING

첫 Spring 프로젝트 + Bean 주입

흐름도에 첫 박스를 그린다

학습 목표

  • Eclipse 에서 Spring Legacy Project 를 만들 수 있다
  • Bean 한 개를 컨테이너에 등록한다
  • @Autowired 로 주입받아 사용한다

오늘의 흐름

1
Spring Legacy Project 생성
2
간단한 Service 클래스 작성 + @Service
3
기본 컨트롤러에서 @Autowired
4
Tomcat 실행 + 브라우저 확인

코드 — Service Bean


package com.example.demo;

import org.springframework.stereotype.Service;

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

코드 — Controller


@Controller
public class HomeController {

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

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

JSP — 화면


<!-- /WEB-INF/views/home.jsp -->
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<body>
    <h1>${msg}</h1>
</body>
</html>

실행 — 브라우저로

스크린샷
크롬에서 localhost:8080/.../ 접속 시 "Spring Bean 으로 인사드립니다!" 가 큰 글씨로 보이는 화면

컨트롤러에 new HelloService() 가 없습니다. 컨테이너가 자동 주입한 결과입니다.

흐름도 확장

브라우저
Controller
Service
(Bean)
JSP 응답
Controller 와 Service 박스가 흐름에 자리잡았습니다 — Part 3 에서 본격 분업

🔄 Before / After

Part 1 끝

Hello Servlet 한 개로 응답을 만들었다.

Part 2 끝

Spring 프로젝트 안에서 Bean 두 개(Service · Controller)가 자동 연결되어 응답을 만든다.

정리

오늘 들고 가는 것

  • Spring Legacy Project 가 어떻게 만들어지는지 안다
  • @Service + @Autowired 로 Bean 주입을 첫 코드로 본다
  • 다음 Part 에서 — MVC 6 계층의 본격 분업

다음 차시(Part 3): MVC — 왜 분업하나.