Spring 입문

박민서·2023년 5월 2일
0

프로젝트 새성

  • 사전 준비물

Java 11 설치
IDE: IntelliJ 또는 Eclipse 설치

스프링 부트 스타터 사이트로 이동해서 스프링 프로젝트 생성
https://start.spring.io

프로젝트 선택

  • Project : Gradle - Groovy Project
  • groupId : 기업명 사용
  • artifactId: 프로젝트 명
  • Dependencies: Spring Web(웹 프로젝트), Thymeleaf(HTML을 만들어주는 템플릿 엔진)

프로젝트 생성

  • src에 main과 test폴더가 나누어져 있음

  • main 안에 java와 resources파일 java밑에 실제 소스파일이 있다

  • test 폴더에는 test코드가 들어가 있음

  • test가 요즘 개발 트렌드에선 굉장히 중요하다

  • resources는 실제 자바 코드파일을 제외한 xml이나 설정파일 html

  • .gitignore에 깃허브에 올라가면 안되는 것들을 적는다

  • build.gradle 버전설정하고 라이브러리 댕겨오는 정도로만 이해

dependencies {
   implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
   implementation 'org.springframework.boot:spring-boot-starter-web'
   testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

SpringApplication.run(HelloSpringApplication.class, args);

  • 웹에서 localhost:8080을 들어가면 Whitelabel Error Page가 뜨면 정상

라이브러리 살펴보기

spring-boot-starter-web -> spring-boot-stater-tomcat/spring webmvc

Gradle은 의존관계가 있는 라이브러리를 함께 다운로드 한다

spring-boot-starter-thyemleafg -> thymeleaf-spring

타임리프와 관련된 라이브러리

  • spring-boot-starter-web을 땅기면 의존관계가 있는 것들을 다 땡겨온 다
  • Dependencies 라이브러리 의존관계가 있는것들
  • 실무에 있는 사람들은 System.out.println으로 출력하면 안됨 로깅으로 해야함 로깅으로 해야 관리가됨 로깅 라이브러리 -> slf4j or logback

테스트 라이브러리

  • spring-boot-starter-test
  • junit: 테스트 프레임워크
  • mockito: 목 라이브러리
  • assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
  • spring-test: 스프링 통합 테스트 지원

View 환경 설정

  • 웹 애플리케이션에서 첫번째 진입점이 바로 controller
package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
@Controller
public class HelloController {
    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello!!");
        return "hello";
    }
} 
  • localhost:8080/hello 라는 요청이 오면 hello 메서드를 실행
  • GetMapping에서 Get은 Http 요청 메서드의 Get이다.
  • hello의 url에 매칭이되면 스프링이 model이라는 것을 만들어 넘기면
    키 값은 data이고 값은 hello!!이다. 값은 바뀔 수 있다.
  • hello를 리턴하면 resources/templates/hello.html을 실행

  • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( viewResolver )가 화면을 찾아서 처리한다.
  • 스프링 부트 템플릿엔진 기본 viewName 매핑
  • resources:templates/ +{ViewName}+ .htm
profile
ㅎㅇㅌ

0개의 댓글