[Spring 입문] 프로젝트 환경설정
<프로젝트 생성>
- Java 11 설치
- IDE: IntelliJ 또는 Eclipse 설치 -> 요즘 다 IntelliJ 씁니다
- 스프링 부트 스타터 사이트로 이동해서 스프링 프로젝트 생성
- 과거에는 Maven 썼는데 요즘은 Gradle로 대부분 넘어왔습니다. Spring Boot 버전은 2.3.1(안정된 버전)으로 합니다. Dependencies에는 Spring Web과 Thymeleaf를 선택합니다.
- build.gradle을 보면 기본적인 설정이 되어있습니다. src폴더의 main의 java안에 main함수를 실행하고, http://localhost:8080/에 접속해서 에러메시지가 뜨면 성공입니다.
<라이브러리 살펴보기>
- Gradle이 의존도를 관리해줍니다. 의존관계가 있는 라이브러리들을 함께 다운로드합니다.
- System.out.println은 거의 안쓰고 logging을 씁니다.
<View 환경설정>
- resources/static/index.html을 만들어주면 welcome page 기능을 제공합니다.
- Thymeleaf라는 템플릿 엔진을 사용합니다.
hello.hellospring/controller/HelloController.java
@Controller
public class HelloController {
@GetMapping("hello") //GET방식
public String hello(Model model){
model.addAttribute("data", "hello!!");
return "hello"; // hello.html로
}
}
resources/templates/hello.html
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>
</body>
</html>
- spring-boot-devtools 라이브러리를 추가하면, 'html'파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경이 가능합니다. (인텔리J 컴파일 방법: 메뉴 Build->Recompile)
<빌드하고 실행하기>
- 콘솔로 이동해서(맥 기준, 저는 git bash를 이용했습니다)
./grandlew build
cd build/libs
java -jar hello-spring-0.0.1-SNAPSHOT.jar
위와 같이 입력한 후 실행을 확인하면 됩니다.
- ./grandlew clean 을 입력하면 build 폴더가 없어집니다. 잘 안될 때 ./grandlew clean build를 입력하면 완전히 지우고 다시 빌드됩니다.