본문 바로가기

개발기술/빌드, 배포, 인프라

스프링 부트 환경설정 (스프링 Init, Package, Configuration)

스프링부트

Spring Boot는 Spring Framework의 모든 기능을 포함하면서도, 개발자가 빠르게 개발을 시작할 수 있도록 추가적인 지원과 도구를 제공합니다. spring initializer(https://start.spring.io/)를 사용한자동 설정을 통해 Spring boot project의 구조를 알아서 만들어준다.  Spring 애플리케이션 구성을 간소화합니다. 반면, Spring Framework는 수동으로 빈을 구성하고 의존성을 주입해야 합니다.

 

스프링부트 프로젝트 생성

  • spring initializer : 스프링 기반으로 프로젝트를 만들어주는 스프링 부트 사이트 (https://start.spring.io/)
    • Project (빌드관리도구) : 라이브러리를 관리해주고 빌드 및 실행을 도와주는 주체
      • Gradle : 최신 gradle, 빌드속도가 빠름, Maven : legacy
    • Project Metadata 
      • Group : 기업명 혹은 도메인 입력 (com.naver.map) 
      • artifact : 프로젝트의 이름. build에 대한 결과물 
    • Packaging :  Java 애플리케이션을 배포하는 방법에 있어 패키징방식 
      • JAR : java archive ;  스탠드얼론 Java 애플리케이션을 단일 실행 가능 파일로 패키징하기 위해 사용됩니다. 이는 내장 HTTP 서버(예: Tomcat, Jetty, Undertow 등)를 포함하여 애플리케이션을 실행하는 데 필요한 모든 것을 포함합니다.
      • WAR : web application archive. war는 일반적으로 내장 HTTP 서버를 포함하지 않습니다. 대신, WAR 파일은 Servlet 컨테이너나 Java EE 애플리케이션 서버(예: Apache Tomcat, Jetty)에 배포되어 실행됩니다. 기업 환경에서 여러 애플리케이션을 중앙 서버에 배포하여 관리할 때 사용됩니다.
    • Java
      • 최신이라고 다 좋은 것은 아니고 LTS(Longterm support) 기한을 보고서 일반적으로 선택함 
    • Dependency
      • 어떤 라이브러리를 불러와서 쓸 것인지 선택 ;Spring Web, Thymeleaf

 

스프링부트 패키지구조

 

디렉토리 트리구조 

  • .gradle : gradle 구동시점에 필요한 숨김파일
  • .idea : intellij 구동시점에 필요한 숨김파일
    • 숨김파일 프로젝트의 임시파일이나 구동시점에서만 필요한 파일들. 개발자가 들어가서 작업할 필요x
  • gradle : build.gradle이 동작한 빌드 결과값

src : 개발자가 작업할 공간

  •  main
    • java : 실제 소스파일
      • JavaSpringApplication  : @SpringbootApplication과 springapplication을 실행시 톰켓이라는 웹서버를  실행함.
      • Controller package : 웹 어플리케이션에서 첫진입점이됨.
    •  resources : html을 포함한 자바 외의 모든 파일
      • static directory에 'index.html'을 생성해주면 정적인 홈페이지를 만들어준다.
      • 동적인 홈페이지를 만들고 싶으면 thymeleaf를 사용해야함.
  • test : test와 main이 분리되어 있으며 이는 최근 test 코드를 중요시하는 트렌드를 반영함.

 

 gitignore : 깃에 올리기 위해서  불필요한 파일들을 제외하는 파일. (.idea나 .gradle처럼 구동시점에만 필요한 코드들 / 개인의 환경설정에 관여하는 코드들)

 

build.gradle : 스프링 부트에서 설정된 셋팅들과 버전설정 및 라이브러리 호출하는 파일로, 프로젝트 첫 빌드시 실행시킴.

 

스프링 부트 라이브러리

 

Spring은 java의 webapplication  전반의 모든 것을 포괄하기때문에 연관된 라이브러리, 툴의 양이 매우 방대하여 모든것을 이해하기 어렵다.대신,documentation을 통해서 검색할 수 있는 능력을 기르는 것이 중요함.

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.3.4'
    id 'io.spring.dependency-management' version '1.1.6'
}

 

 

Plugins: Plugins extend Gradle itself and modify the build process by adding tasks, configurations, and dependencies specific to a certain type of project. They are typically used to manage aspects of the project lifecycle like compiling code, running tests, or packaging applications.

  • id 'io.spring.dependency-management' version '1.1.6': This plugin manages dependencies and ensures consistent versions for libraries. It helps ensure that your Spring Boot dependencies and their transitive dependencies are handled correctly.
group = 'com.zerobase'
version = '0.0.1-SNAPSHOT'

 

  • group = 'com.zerobase': Defines the group ID of your project. It's typically used to identify your project in Maven Central or other repositories.
  • version = '0.0.1-SNAPSHOT': Specifies the project version. SNAPSHOT indicates that this is a development version.
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

toolchain: The toolchain allows you to specify which version of the Java Development Kit (JDK) to use. In this case, the code sets Java 17 (JavaLanguageVersion.of(17)).

onfigurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

 

compileOnly: This is a configuration for dependencies that should only be available at compile time, but not at runtime.

  • extendsFrom annotationProcessor: This ensures that the compileOnly configuration inherits from annotationProcessor, which is used for annotation processing (e.g., with Lombok).
repositories {
    mavenCentral()
}

 

mavenCentral(): Defines the Maven Central repository as the source for resolving dependencies. Maven Central is one of the most widely used repositories for Java projects.

 

 

 

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.14.1'
    
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation 'org.springframework.boot:spring-boot-starter-logging'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

    implementation 'org.hibernate:hibernate-spatial:6.5.3.Final' // Hibernate Spatial
    implementation 'org.locationtech.jts:jts-core:1.18.2' // JTS Core Library
}

 

스프링 기본 라이브러리

  • spring-boot-starter(공통): 스프링부트 기본 라이브러리로 아래를 포함 (스프링 부트 스프링 코어 로깅기능)
    • spring-boot :spring-core
    • spring-boot-starter-logging : logback, slf4j

스프링 웹 라이브러리 

  • Spring의 Web dependency
    • Spring web service : soap기반으로  사장됨
    • Spring web : MVC기반으로 현재 가장 대중적으로 사용됨. 아래를 포함함.
      • spring-boot-starter-tomcat: 톰캣 (웹서버), spring-webmvc: 스프링 웹 MVC
    • Spring Reactive : 비동기 non-blocking기술을 사용함
      • spring webflux
      • spring netty
  •  spring-boot-starter-thymeleaf: 타임리프 템플릿 엔진(View)을 사용하는 라이브러리

스프링 데이터베이스 라이브러리

  • spring-boot-starter-data-jpa : hibernate를 사용한 데이터베이스 접근 라이브러리
  •  h2 database: 테스트용 데이터베이스

 

스프링 테스트 라이브러리** 

  • spring-boot-starter-test : spring에서 기본적으로 포함되며 아래를 포함
    • junit: 테스트 프레임워크
    • mockito: 목 라이브러리
    • assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리 
    • spring-test: 스프링 통합 테스트 지원

기타라이브러리

  • Lombok: 어노테이션기반 유틸리티 라이브러리
  • spring-boot-starter-validation : bean validation을 위한 의존성
tasks.named('test') {
    useJUnitPlatform()
}

 

 

 

프로젝트 환경 설정

application.yml 또는 application.properties 파일은 Spring Boot 애플리케이션의 설정 정보로서 Spring 동작의 Parameter역할을 하고 있다고 생각하면 된다.  파일을 통해 애플리케이션의 동작 방식을 설정할 수 있다. 여기에는 데이터베이스 연결 정보, JPA 설정, 서버 포트, 로깅 설정 등 다양한 애플리케이션 관련 설정이 포함될 수 있습니다.

  환경은 일반적으로 로컬환경, 개발테스트환경, 실제운영환경 보통 3가지 환경이 존재하며, 각 환경마다 바라보는 DB와 같은 설정이 다르다. 코드 상에서는 환경과 무관하게 작동하도록 작성하고, 환경별로 분리되는 내용은 환경설정인 (yml/properties) 값에 담는다.

 

데이터베이스 datasource 연결 정보

데이터베이스와 연결하기 위한 설정을 정의합니다. 이는 데이터베이스 URL, 사용자 이름, 비밀번호, 드라이버 클래스 등을 포함합니다.

 

spring:
  datasource:
    url: jdbc:h2:mem:test
    username: sa
    password:
    driverClassName: org.h2.Driver
  h2:
    console:
      enabled: true
  jpa:
    defer-datasource-initialization: true
    database-platform: H2
    hibernate:
      ddl-auto: create-drop
    open-in-view: false
    properties:
      hibernate:
        format_sql: true
        show_sql: true

 

spring.datasource Section

  •  url : JDBC connection URL로 JDBC (Java Database Connectivity) API에게 DB연결과 관련된 Parameter을 제공한다고 볼수 있다.  어떤 데이터베이스와 어떻게 연결할지에 대한 설정을 진행한다. 
    • JDBC URL은 일반적으로 다음과 같은 형태를 따른다. jdbc:[database-type]:[connection-details]
    • 여기서 jdbc:h2:mem:test : mem은 in-memory구조를 지칭하며, test는 테스트 목적임을 지칭한다. 이와 같이 jdbc url을 통해서 연결할 데이터베이스의 타입을 정할수 있다.
    • url다음에 ; 기호 뒤에 custom을 위한 특수한 파라미터가 올 수 있다.
      • DB_CLOSE_DELAY=-1: parameter specific to H2. It tells the database to remain open after the last connection is closed
      • INIT=RUNSCRIPT FROM 'classpath:sql/h2gis-init.sql' : INIT is an instruction to H2 that tells it to initialize , RUNSCRIPT FROM 'classpath:sql/h2gis-init.sql': This part specifies the location of the SQL script (h2gis-init.sql) in the classpath
  • username : DB의 사용자이름 
  • password : DB의 Pw
  • driver-class-name : 어떤 jdbc driver을 사용할지 선택해줌 (org.h2.Driver). If you specify the url (like jdbc:h2:mem:testdb), Spring Boot will automatically infer the correct JDBC driver from the URL. So, in many cases, you don’t need to explicitly specify the driver-class-name because Spring Boot can infer it from the URL.

 

spring.h2 section

  • h2
    • console :enabled : h2-console이라는 url을 통해서 h2 db 조작을 가능하게하는 콘솔창을 활성화할지 결정한다.

spring.jpa Section

  • JPA / Hibernate Settings :   how entities are managed and how schema generation is handled.  
    • defer-datasource-initialization : 테이블에 초기데이터/테이블 스키마를 메뉴얼로 설정해주고 싶을때 사용. 테이블이 생성될때까지 Sql 스크립트의 실행을 지연시키고 hibernate가 table을 생성한 후 작동하도록 조절함. 
      • resource아래에 두 파일이 위치해야만 springboot에서 파일을 인식하고 동작시킨다.
      • schema.sql: For schema-related SQL commands (e.g., table creation, indexes).
      • data.sql: For inserting initial data.
    • data-base-platform : Tells Hibernate to use the which DB dialect for generating SQL statements.
    • hibernate
      • ddl-auto:  data delete automation 테이블 및 스키마의 생성과 삭제를 자동으로 관리하는 기능 
        • create : :어플리케이션 가동 시점에 테이블 생성
        • create-drop  :어플리케이션 가동 시점에 테이블 생성, 종료시점에 테이블 삭제
        • validate : Hibernate는 애플리케이션에서 정의한 엔티티와 데이터베이스의 테이블이 일치하는지 검증합니다. 테이블과 스키마가 일치하지 않으면 오류를 발생시킵니다.
        • update : Hibernate가 데이터베이스 스키마와 애플리케이션 엔티티 간의 차이를 감지하고, 필요한 경우 스키마를 수정합니다. 그러나 기존 데이터를 삭제하지 않고 테이블이나 컬럼을 추가하거나 수정하는 방식으로 작동합니다.
      •  defer-datasource-initialization: true ensures that any SQL scripts (like schema.sql) run after Hibernate has created the tables.
    • properties
      • hibernate:
        • dialect : Tells Hibernate to use the which DB dialect for generating SQL statements.
        • format_sql : hibernate에서 실행하는 sql statement를 보기좋은 포맷으로 만듬
        • show_sql :  hibernate에서 실행하는 sql statement를 출력하여 보여줌
  • H2 연결설정 : h2: console : enabled : true

 

서버 포트 설정

애플리케이션이 실행되는 포트를 설정할 수 있습니다. 기본적으로 Spring Boot 애플리케이션은 포트 8080에서 실행됩니다.

Server Configuration : Basic server configurations such as port, context path, and session settings.

server:
  port: 8080
  servlet:
    context-path: /api
  tomcat:
    max-threads: 200
  • Security Settings: Configurations related to security, such as authentication methods, password encoding, and security headers.   
spring:
  security:
    user:
      name: admin
      password: admin123
    oauth2:
      client:
        registration:
          google:
            clientId: id
            clientSecret: secret



  • Logging Configuration : Define logging levels, log file paths, and configure different logging frameworks.

로깅 설정

애플리케이션의 로깅 수준과 형식을 설정할 수 있습니다. Spring Boot는 기본적으로 다양한 로깅 프레임워크를 지원합니다.

 

 

logging:
  level:
    org.springframework: DEBUG
    com.myapp: INFO
  file:
    path: /var/log/myapp.log
  • Profile-Specific Configuration : Manage settings for different environments using profiles, such as development, testing, and production.
spring:
  profiles:
    active: dev

---

spring:
  config:
    activate:
      on-profile: dev
  datasource:
    url: jdbc:h2:mem:testdb
    username: sa
    password:

---

spring:
  config:
    activate:
      on-profile: prod
  datasource:
    url: jdbc:mysql://production-host/mydb
    username: produser
    password: prodpass
  • Messaging and Email Settings : Configuration for messaging systems like RabbitMQ, Kafka, or email services.
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

  mail:
    host: smtp.example.com
    username: user
    password: pass
    properties:
      mail:
        smtp:
          auth: true
          starttls: enable
  • External Service Configuration : Integrate with external services or APIs, including configuring API keys, endpoints, and other connection details.
app:
  weather-api:
    url: http://api.weatherapi.com/v1/current.json
    key: your-api-key
  • Application-Specific Custom Properties : Define custom application-level properties that are specific to the business logic or operational parameters.
app:
  pagination:
    default-size: 20
  feature:
    enable-new-feature: true

기타설정

  •  

1. 애플리케이션 설정

 

2. 환경별 설정

Spring Boot는 프로파일을 통해 환경별로 다른 설정을 적용할 수 있습니다. 예를 들어, 개발 환경에서는 application-dev.yml, 프로덕션 환경에서는 application-prod.yml 파일을 사용할 수 있습니다. 이를 통해 개발, 테스트, 운영 환경에서 다른 설정을 쉽게 적용할 수 있습니다.

고유Key설정

API Key값과 같이 환경마다 분리하여 관리하여야 하는 값이 있다면 property 파일에 해당 값을 설정하고, 변수위에 @value("${key이름.key}")로 맵핑 한다면 환경변수의 값에서 값을 injection 해준다. 참고적으로 "${key이름.key}"는 SpEL로 환경변수를 가져오는 것

'개발기술 > 빌드, 배포, 인프라' 카테고리의 다른 글

Git 그리고 GitHub  (0) 2024.09.16
SQL과 NoSQL  (0) 2024.09.02
인프라 확장  (0) 2024.09.02
Test 코드 작성  (1) 2024.07.22
Command-Line Instructions(CLI)  (0) 2024.01.24