▣ LAB · SPRING

Spring 프로젝트 첫 실행

첫 Spring 프로젝트 + Bean 주입 — 실습 / 약 30분

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

사전 준비

1
Spring Legacy Project 생성
  1. Eclipse 메뉴: File → New → Other...
  2. 「Spring」 폴더 → Spring Legacy Project
  3. Project Name: spring-demo
  4. Template: Spring MVC Project 선택
  5. 패키지명: com.example.demo (점 3 개 이상 필수)
  6. Finish
스크린샷
Spring Legacy Project 마법사의 Spring MVC Project 템플릿 선택 화면
CHECKPOINT
  • Project Explorer 에 자동 생성된 폴더 구조가 보이나요? (src/main/java, src/main/webapp, pom.xml 등)
2
⚠️ Maven Update Project

프로젝트 우클릭 → Maven → Update Project... → OK

처음에 의존성을 다운로드하는 시간이 좀 걸릴 수 있습니다. 인터넷 연결 확인.

CHECKPOINT
  • Maven Dependencies 폴더에 spring-* jar 들이 보이나요?
3
HelloService 작성

src/main/java/com/example/demo 패키지에 새 클래스 HelloService:

package com.example.demo;

import org.springframework.stereotype.Service;

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

템플릿이 자동 생성한 HomeController 를 다음으로 교체:

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";
    }
}
CHECKPOINT
  • 빨간 줄이 있나요? import 가 모두 제대로 들어왔는지 확인.
5
JSP 수정

src/main/webapp/WEB-INF/views/home.jsp 를 다음으로 교체:

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head><title>Hello Spring</title></head>
<body>
    <h1>${msg}</h1>
</body>
</html>
6
Run on Server
  1. 프로젝트 우클릭 → Run As → Run on Server
  2. 전 차시에서 등록한 Tomcat 선택 → Finish
  3. Console 에 startup 로그 확인
  4. Eclipse 내장 브라우저(또는 외부 크롬)에 화면 등장
스크린샷
"Spring Bean 으로 인사드립니다!" 가 큰 글씨로 보이는 결과 화면
예상 결과

주소창: http://localhost:8080/spring-demo/
화면: Spring Bean 으로 인사드립니다!

CHECKPOINT — 그 사이에 일어난 일
  • Tomcat 시작 시 컨테이너가 HelloServiceHomeController 를 모두 Bean 으로 등록
  • Controller 가 만들어질 때 @Autowired 자리에 HelloService 자동 주입
  • 요청이 오면 Controller 가 Service 를 호출 → 결과를 모델에 담고 → JSP 가 화면 생성
7
실험 — Bean 등록 빼보기

HelloService 의 @Service 를 잠시 주석 처리하고 다시 실행해보세요. 무엇이 일어나나?

// @Service  ← 주석!
public class HelloService { ... }
예상 결과

500 Server Error. Console 에 「No qualifying bean of type 'HelloService' available」 같은 메시지.

이걸 보고 다시 @Service 를 살리세요. 「Bean 등록」이 없으면 「자동 주입」이 불가능하다는 사실 체감.

실습 완료 체크리스트

Spring Legacy Project 생성
Maven Update Project 실행
HelloService Bean 작성
HomeController 에서 @Autowired
JSP 의 ${msg} 표현식
Tomcat 실행 후 화면 확인
@Service 제거 시 에러 직접 봄