Web/Spring
[SpringBoot] 작업 환경 분리: spring.profiles.active 옵션 활용
youngyin
2024. 3. 18. 23:00
환경분리
Spring Boot를 사용하여 프로젝트를 개발할 때, 각각의 작업 환경에 대해 설정을 분리하고 싶은 경우가 있다. 이글에서는 spring.profiles.active 옵션을 사용하여 Spring Boot 애플리케이션의 작업 환경을 분리하는 방법을 정리하고자 한다.
필요성
- 개발, 테스트, 프로덕션 환경에서는 각기 다른 설정이 필요.
테스트서버, 프로덱션용 서버는 보통 분리하는 경우가 많은데, 개발 환경을 분리하여 각 환경에 맞는 데이터베이스에 연결하는 등 다르게 설정할 수 있다. 예를 들어서, 현재 진행하고 있는 프로젝트에서는 이미지저장소 및 데이터 베이스를 환경에 따라 다르게 채택하였다.
- 이미지 저장소 및 데이터베이스 설정
profile | 설명 | 이미지저장소 | 데이터베이스 |
---|---|---|---|
test | 테스트환경 | 로컬 경로(${project.dir}/src/main/resources/images/) | H2 DB Embedded Mode |
dev | 운영환경 | S3 | MariaDB(RDS) |
프로젝트 설정
- Spring Boot 3.0.1
- Java17
- Gradle
application.yml로 환경분리하기
설정파일 application.yml 작성하기
- application-test.yml
# 데이터베이스 설정
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password: password
# 이미지 저장소 설정
image:
storage:
type: local
max-upload-size: 500KB
- application-prd.yml
# 데이터베이스 설정
datasource:
url: jdbc:mariadb://your-cloud-host:3306/your-database
driver-class-name: org.mariadb.jdbc.Driver
username: your-username
password: your-password
# 이미지 저장소 설정
image:
storage:
type: S3
max-upload-size: 100KB
알맞은 설정값 매핑하기
- 방법1) VM option 설정하기
`Dspring.profiles.active`옵션에 환경을 명시하면, 알맞은 `application.yml` 파일을 읽어온다.
java -jar -Dspring.profiles.active=test apiService.jar
java -jar -Dspring.profiles.active=prd apiService.jar
- 방법2) 연결할 설정파일을 직접 지정
경우에 따라서는 외부에 설정파일을 두고, 어떤 파일에 연결할지 직접 지정할 수 있다.
java -jar -Dspring.config.location=classpath:/application-prd.properties apiService.jar
java -jar -Dspring.config.location=classpath:/application-test.properties apiService.jar
더 공부할점
옵션명 `Dspring.profiles.active`이 길어서 사용하기 불편했다. 이러한 경우, gradle에 사용자 태스크를 정의하여 사용할 수 있다.
// 사용자 정의 프로파일을 저장할 변수
def customProfile = ""
// 사용자 정의 옵션을 처리하여 프로파일을 설정하는 함수
def setProfileFromArgs() {
if (project.hasProperty('profile')) {
customProfile = project.property('profile')
// 사용자 정의 옵션에 따라 프로파일 설정
systemProperty 'spring.profiles.active', customProfile ?: 'default'
}
}