[스프링부트] SpringProfile로 개발환경 분리

귤쳥·2022년 9월 16일
0

별 헤는 밤 고치기

목록 보기
2/3
post-thumbnail

매번 주석처리로 환경마다 바꿨던 설정을 분리해보자

설정파일 변경

properties → yaml

  • 장점
    • 가독성이 좋다(계층구조로 표현, 불필요한 소스 중복 제거)
    • 리스트 표현이 간단
    • SpringBoot Profile 적용이 간단함 properties의 경우에는 여러파일로 분리해서 관리해야 하나 yaml은 한 파일내에서 구분하여 사용이 가능하다

코드의 경우 컨버트 사이트를 이용하면 쉽게 옮길 수 있다.
Yaml Converter - MAGEDDO

Spring Profile

개발환경과 실제 서비스용 환경에 설정이 다른경우(디비 설정, 로깅 레벨) 설정파일을 주석처리하고 해제하여 사용하고 있었다. 비효율적이었기 때문에 실행환경에 맞게 설정파일을 정리할 수 있도록 도와주는 SpringProfile을 사용해 볼 것이다.

  • spring.config.activate.on-profile (스프링부트2.4.0이후에 기존사용하던 spring.profile이 deprecated되어서 사용하지 않음) 프로파일 활성화시 사용할 속성을 정의
  • spring.profiles.group 프로파일을 그룹으로 묶어서 적용가능하다. local을 활성화하면 localdb와 common 두개의 프로파일을 한번에 실행가능하다.
spring:
  profiles:
    group:
      "local": "localdb,common"
      "prod":  "proddb,common"
---

spring: #prod DB환경
  config:
    activate:
      on-profile: "proddb"
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: 이름
    url: 주소
    password: 비번
  jpa:
    show-sql: 'false'
    hibernate:
      ddl-auto: update

---
spring: #local DB환경
  config:
    activate:
      on-profile: "localdb"
  datasource:
    driver-class-name: org.h2.Driver
    username: 
    url: jdbc:h2:tcp://localhost/~/tourApiProject
  jpa:
    show-sql: 'true'
    hibernate:
      ddl-auto: create

---
spring: #공통환경
  config:
    activate:
      on-profile: "common"
  sql:
    init:
      mode: always
  servlet:
    multipart:
      maxFileSize: 100MB
      maxRequestSize: 100MB
server:
  tomcat:
    connection-timeout: 5000

resources 폴더 분리

환경별 파일 분리

resources-[환경명]으로 디렉토리를 만들어서 환경별로 다르게 사용하고 싶은 파일을 해당 디렉토리로 이동시켜주면 된다.

build.gradle 파일

기본 프로파일은 local로 설정한다.

  • ext변수

project레벨의 build.gradle 에 ext.name형태로 변수를 선언할 수 있다.

프로젝트 전체에서 사용 가능하다.

//프로젝트 단위 변수 설정
ext {
	profile = (!project.hasProperty('profile') || !profile) ? 'local' : profile
}
//리소스 폴더 지정
sourceSets{
	main{
		resources{
			srcDirs "src/main/resources", "src/main/resources-s%{profile}"
		}
	}
}

+gradle 설정파일, 빌드파일

settings.gradle

빌드단위(멀티프로젝트여도 한개반 존재)
프로젝트 수준 저장소 설정을 정의하고, 앱을 빌드할 때 포함해야 하는 모듈을 Gradle에 알려줍니다. 멀티 프로젝트를 빌드할 때 사용

build.gradle

프로젝트 단위(멀티 프로젝트면 려러개 존재)
프로젝트의 모든 모듈에 적용되는 종속 항목을 정의합니다. 기본적으로 최상위 빌드 파일은 plugins
블록을 사용하여 프로젝트의 모든 모듈에 공통되는 Gradle 종속 항목을 정의합니다. 또한 최상위 빌드 파일에는 빌드 디렉터리를 정리하는 코드가 포함되어 있습니다.

활성화 방법

실행시 profile을 선택해서 실행하면 된다.

  • Jar
java -jar myapp.jar --spring.profiles.active=prod
  • Intellij
  1. Run> EditConfiguration
  2. Spring Boot Application
  3. Active Profiles에서 원하는 프로파일명 선택

*위에 default를 local로 설정해 놓았기 때문에 따로 설정안해도 잘 실행되기는 한다.

(우리는 local로 설정!)

에러

  • Entry application.yml is a duplicate but no duplicate handling strategy has been set.

공통 resource폴더, profile별 resource폴더를 따로 만들고 둘다 불러오는 경우가 있는경우 중복으로 가져왔다는 에러이다.

sourceSets{
	main{
		resources{
			srcDirs "src/main/resources", "src/main/resources-s%{profile}"
		}
	}
}

가져온 리소스를 어떻게 처리할 지 지정해주면 된다.

duplicatesStrategy에 INCLUDE 또는 EXCLUDE로 지정해준다.

(둘다 포함이니까 INCLUDE로 지정하겠다.

tasks{
	processResources{
		duplicatesStrategy = org.gradle.api.file.DuplicatesStrategy.INCLUDE
	}
}

결과

build폴더를 보면 프로파일에서 설정한 리소스폴더만 참조하는 것을 볼 수 있다.

출처

https://docs.gradle.org/current/userguide/building_java_projects.html#sec:custom_java_source_set_paths

https://derveljunit.tistory.com/336

profile
혼긱 CE의 이제 막 시작하는 코딩

0개의 댓글