Spring

Spring Boot - Overview

728x90

참조한 강의 : www.udemy.com/course/spring-hibernate-tutorial/

 

 

이전 포스팅 까지는 Spring Framework 에 대한 기본 개념들과 기초적인 예제들을 학습해보았다

 

이번에는 Spring Boot 에 대해서 알아본다

 

 

 

* Spring Boot 가 만들어진 이유

: Spring Boot 가 만들어진 이유는 

 

첫번째로, 기존의 Spring Framework 는 진입하기 위해서 필요한 사전지식이 너무 방대하다

(물론 결국에는 다 알고 있어야 하기는 하지만, 시작 하는 입장에서는 상당히 부담스러운 면이 있다)

 

두번째로, 기존의 Spring Framework 는 의존성 모듈을 일일이 전부 관리해줘야 했다

(물론 Spring Boot 도 필요한 모듈들을 받아와야 하긴 하지만, spring boot 에서는 spring-boot-stater-* 라는 형식으로 여러 모듈들을 한꺼번에 담아서 묶음 처리하기 때문에, 모든 모듈을 일일이 관리하는 기존의 spring 보다는 좀 더 간소화 되었다)

 

 

* Spring Boot 프로젝트 생성

: Spring Boot 프로젝트를 만들기 위해서는 아래의 사이트에 가면 매우 간편하게 설정하여 JAR 파일을 받아올 수 있다

start.spring.io/

 

 

 

버전 선택 부분에서 SNAPSHOT 은 아직 안정화 되지 않은 버전이고 (Beta 버전)

M3 또한 마찬가지다

 

그래서 괄호표시가 붙지 않은 버전 중 최신 버전을 선택해서 고르면 되고,

좌측 하단에는 프로젝트 메타 데이터를 설정하고 우측에는 프로젝트에 추가할 모듈을 설정한다

 

이렇게 설정하고 나서 JAR 파일을 받아오면

spring boot 의 특이한 점 중 하나로 JAR 파일 내에 이미 톰캣 같은 서버가 이미 내장 되어서 나온다

 

그래서 별도로 톰캣 같은 서버 설정을 해줄 필요가 없다

 

 

* Spring Boot 프로젝트의 기본 폴더 구조

maven 기반의 프로젝트를 만든 경우 기본적으로 아래와 같은 구조를 갖는다

 

 

주의할점은 프로젝트를 구성하면서 만들어나갈 Controller, AOP, REST 등의 비지니스 로직을 위한 코드들은 전부 프로젝트의 메인 함수가 담긴 파일 아래에 위치해야 된다.

 

위에 그림에서는 메인 함수가 담긴 파일은 MyFirstApplication.java 이고 

REST Controller 를 표현하는 FunRestController.java 는 MyFirstApplication 하위 폴더 소속이다

 

이렇게 되는 이유는 별도의 설정없이 기본 스프링 부트 프로젝트를 만들면, 

ComponentScan 의 범위가 메인 함수가 있는 파일의 하위 폴더들을 탐색하도록 되어 있기 때문이다

즉 @ComponentScan("com.luv2code.springboot.demo.myfirstapp.*) 이라고 볼 수 있는것.

 

 

* 의존성 모듈 관리

: Spring Boot 는 의존성 모듈을 프로젝트에 주입할때, Spring Framework 에서 했던것처럼 일일이 다 받아올 필요가 없다

 

예를들어, Spring Framework 에서 web 과 web-mvc 모듈을 받아오기 위해서는 

pom.xml 에 각각 의존성 주입을 위한 설정을 따로 코드를 써줘야 했다.

 

- 기존의 pom.xml

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.3.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.4</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
cs

 

그러나 이렇게 일일이 다 받아오지 않아도 다음과 같이 개선한 형태로 사용할 수 있게 되었다

 

- 개선된 pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
cs

spring-boot-starter-web 이라는 의존성 모듈 하나로 spring web 관련 모든 모듈들을 포괄하고 있다

 

여기서 parent 라는 못보던게 보이는데, 이는 spring boot 프로젝트가 다른 의존성 모듈들을 주입할때

위에서 보는 것처럼 version 을 따로 명시를 해주지 않고 parent 에서 작성한 version 을 가지고 전체 다른 모듈들에 적용하기 위해서 사용된다

 

parent 에 2.4.3 이라고 지정했으므로 spring-boot-stater-web 또한 2.4.3 버전이 되는 것이다.

 

이런식의 방식은 굳이 모듈 하나하나 전체를 버전 관리해주지 않아도 된다는 장점이 있다

 

 

* Spring Boot Dev Tools

: 기본 스프링 부트 프로젝트는 프로젝트 코드에 어떤 변화가 나타났을때, 자동으로 재시작되지 않는다

매번 코드 수정하고 서버 다시 실행해서 점검하는 방식은 매우 비효율적일 수 있다.

이런 단점을 보완하고자 등장한게 spring boot dev tools 이다

 

이 모듈에 대한 의존성 주입은 다음과 같이 하면 된다

 

- pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>
cs

 

이클립스 IDE 의 경우 자동실행이 되지만 Intellij IDEA 의 경우 자동 재실행이 안된다

 

이에 대한 해결책은 아래의 링크를 참조

mkyong.com/spring-boot/intellij-idea-spring-boot-template-reload-is-not-working/

 

Intellij IDEA – Spring boot reload static file is not working - Mkyong.com

- Intellij IDEA – Spring boot reload static file is not working

mkyong.com

 

 

* Spring Boot Actuactor

: Spring Boot 프로젝트의 health 와 info 등의 정보를 알 수 있게 해주는 모듈이다.

actuator 의 종류는 아래의 링크에 가면 더 자세히 볼 수 있다

 

docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html

 

Spring Boot Actuator: Production-ready Features

HTTP Tracing can be enabled by providing a bean of type HttpTraceRepository in your application’s configuration. For convenience, Spring Boot offers an InMemoryHttpTraceRepository that stores traces for the last 100 request-response exchanges, by default

docs.spring.io

아래와 같이 actuator 모듈을 의존성 주입해주고

 

- pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
cs

 

프로젝트를 실행시키고 

/actuator/health 와 /actuator/info 에 가면 

프로젝트의 상태정보와 프로젝트 메타데이터를 볼 수 있다

/actuator/info 의 경우 처음엔 아무 값도 들어가 있지 않다

그래서 properties 파일에 아래 처럼 직접 추가해주면 보이게 된다

 

- application.properties

info.app.name=My First Spring Boot App
info.app.description=funny project
info.app.version=1.0.0
info.app.a=test property
cs

 

 

이것 말고도 다른 url 을 보고 싶으면 

application.properties 파일에 다음과 같은 문구를 추가한다

 

- application.properties

management.endpoints.web.exposure.include=*
cs

그러나 이렇게 전체 url 을 보게 하면 프로젝트에 대한 민감한 정보가 외부에 쉽사리 노출 될 수 있다

 

그러므로, spring security 를 추가해줘서 접근을 제한 시켜야한다

혹은 properties 파일에 management.endpoints.web.exposure.exclude 값을 넣어서 제한할 수 도 있다

 

spring boot 에서 spring security 는 spring-boot-stater-security 모듈을 의존성 주입하면 된다

 

- pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
cs

 

- application.properties

management.endpoints.web.exposure.exclude=health, info
cs

(/actuator/health, /actuator/info 만 접근제한 해둔 예제)

 

 

 

* Spring Boot 를 CLI 환경에서 실행하기

: IDE 를 쓰지 않고 CLI 에서 실행하려면 두가지 방법이 있다

 

첫번째는 java -jar 명령어를 이용하는 것이다

먼저 프로젝트 폴더 위치로 가서 mvnw package 명령어를 작성하면 프로젝트가 빌드 된다

빌드된 결과는 프로젝트 폴더의 target 폴더에 ~.jar 형식으로 빌드되어 있다

target 폴더로 이동하여 

java -jar ~.jar 명령어를 입력하여 실행하면 다음과 같이 CLI 에서 실행되는 것을 볼 수 있다

 

 

두번째는 mvnw spring-boot:run 명령어를 이용한다

이 명령어는 빌드 과정이 따로 필요없고 target 폴더가 아니라 프로젝트 루트 폴더에 가서 사용하면 된다

 

 

 

 

* Spring Boot Properties

: 스프링 부트 프로젝트 관련 설정 값을 만들때 보통 properties 파일에 저장해두곤 한다

 

개발자가 직접 작성하는 설정값 외에도 스프링 부트가 기본적으로 제공하는 설정 값이 매우 많이 존재한다

아래의 링크에 가면 더 자세히 볼 수 있다

docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties

 

Common Application properties

Various properties can be specified inside your application.properties file, inside your application.yml file, or as command line switches. This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume

docs.spring.io

이 사이트에 가면 16개의 카테고리로 나눠서 설명이 되어 있는데 

예를들어 web 카테고리의 경우, 스프링 부트 프로젝트의 서버 포트 번호 설정하는 부분이나 context path 를 설정하는 부분 등 이 작성되어 있다.

 

 

728x90

'Spring' 카테고리의 다른 글

Spring Boot - Spring Data REST  (0) 2021.03.25
Spring Boot - DAO  (0) 2021.03.24
Intellij 에 Spring Framework 설정하기  (0) 2021.03.14
Spring REST - REST Controller  (0) 2021.03.11
Spring REST - Overview  (0) 2021.03.07