첫 Spring 프로젝트 + Bean 주입 — 실습 / 약 30분
File → New → Other...Spring Legacy Projectspring-demoSpring MVC Project 선택com.example.demo (점 3 개 이상 필수)src/main/java, src/main/webapp, pom.xml 등)프로젝트 우클릭 → Maven → Update Project... → OK
처음에 의존성을 다운로드하는 시간이 좀 걸릴 수 있습니다. 인터넷 연결 확인.
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 으로 인사드립니다!";
}
}
템플릿이 자동 생성한 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";
}
}
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>
Run As → Run on Server주소창: http://localhost:8080/spring-demo/
화면: Spring Bean 으로 인사드립니다!
HelloService 와 HomeController 를 모두 Bean 으로 등록@Autowired 자리에 HelloService 자동 주입HelloService 의 @Service 를 잠시 주석 처리하고 다시 실행해보세요. 무엇이 일어나나?
// @Service ← 주석!
public class HelloService { ... }
500 Server Error. Console 에 「No qualifying bean of type 'HelloService' available」 같은 메시지.
이걸 보고 다시 @Service 를 살리세요. 「Bean 등록」이 없으면 「자동 주입」이 불가능하다는 사실 체감.
@Autowired${msg} 표현식@Service 제거 시 에러 직접 봄