흐름도에 첫 박스를 그린다 — 읽기 자료
여기까지 우리는 IoC/DI 의 발상, Spring 의 어노테이션, Maven, 환경 구축을 차례로 배웠습니다. 이제 이걸 한 프로젝트로 합쳐봅니다.
Eclipse 메뉴: File → New → Spring Legacy Project → Spring MVC Project. 패키지명은 com.example.demo 같은 점 3 개 형식.
점이 최소 3 개 들어가야 합니다 (예: com.example.demo). 점이 2 개면 마지막이 컨트롤러 패키지가 되어 다른 패키지가 인식 안 되는 함정.
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
public String getMessage() {
return "Spring Bean 으로 인사드립니다!";
}
}
@Service 한 줄이 이 클래스를 컨테이너의 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 가 컨테이너에서 알아서 가져옵니다.
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<body>
<h1>${msg}</h1>
</body>
</html>
${msg} 는 컨트롤러가 모델에 담아준 값. EL(Expression Language) 문법.
Servlet 한 개로 응답.
Spring 프로젝트 안에서 Bean 들이 자동 연결되어 응답을 만든다. 다음 Part 에서 MVC 의 본격 분업.