공부 기록/Spring

[Spring Boot] 다중 Profile을 사용해서 환경 별 구성 다르게 하기

뵤옹 2023. 10. 23. 14:47

Spring Boot에서는 Spring Profiles을 사용하여 각 Profile에 따라 환경 구성을 다르게 설정할 수 있다.

로컬, 테스트, 운영 서버 등 프로젝트를 진행하면서 달라지는 환경 설정(DB, port 등)을 다중 Profile을 사용하면 매번 환경 설정을 수정할 필요없이 적용 가능하다.

Profile 설정은 properties 파일 또는 yml 파일에 저장해두는데, 해당 포스팅은 properties 파일을 사용하여 다중 profile을 설정하는 방법을 작성하려고 한다.

참고로, 아래의 코드는 Spring Boot와 mybatis를 연동한 설정값도 포함하고 있다.

 

기본 개발 환경

  • Spring Boot 2.7.11
  • 데이터베이스: postgreSQL
  • IntelliJ 

 

환경 별 properties 파일 나누기

환경 별 properties 파일을 생성하여 환경 Profile을 설정하기 위해서는

파일 명을 application-{profile}.properties로 생성하면 된다.

각 Profile에 대한 properties 파일 생성 후, 파일 내부에 각 Profile에 맞는 환경 설정을 작성하면 된다.

application-local.properties

spring.datasource.hikari.maximum-pool-size=4

spring.datasource.url=jdbc:postgresql://[개발환경IP]:[개발환경PORT]/[개발환경DB명]?characterEncoding=UTF-8&serverTimezone=Asia/Seoul
spring.datasource.username=
spring.datasource.password=
spring.datasource.hikari.schema=
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.type-aliases-package=com.testing.ananlysite.model
mybatis.mapper-locations=classpath:mapper/local/*.xml

server.servlet.context-path=
server.port=

 

application-prod.properties

spring.datasource.hikari.maximum-pool-size=4

spring.datasource.url=jdbc:postgresql://[개발환경IP]:[개발환경PORT]/[개발환경DB명]?characterEncoding=UTF-8&serverTimezone=Asia/Seoul
spring.datasource.username=
spring.datasource.password=

spring.datasource.hikari.schema=
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.type-aliases-package=com.testing.ananlysite.model
mybatis.mapper-locations=classpath:mapper/prod/*.xml

server.servlet.context-path=
server.port=

 

application.properties

spring.profiles.active: prod

 

한 application.properties에 작성하기

이전에는 yml 파일만 한 파일 안에 다중 Profile을 설정할 수 있었고, properties 파일은 위와 같이 Profile 별로 properties 파일을 따로 만들어 사용해야 했다.

 하지만 Spring Boot 2.4 버전부터는 하나의 properties 파일에 '#---'을 사용하여 여러 Profile을 구분, 설정할 수 있다.

spring.profiles.active=prod
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.type-aliases-package=com.testing.ananlysite.model
#---
spring.config.activate.on-profile=local
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.hikari.maximum-pool-size=4
spring.datasource.url=jdbc:postgresql://[개발환경IP]:[개발환경PORT]/[개발환경DB명]?characterEncoding=UTF-8&serverTimezone=Asia/Seoul
spring.datasource.username=
spring.datasource.password=
spring.datasource.hikari.schema=
server.servlet.context-path=
server.port=
mybatis.mapper-locations=classpath:mapper/local/*.xml
#---
spring.config.activate.on-profile=prod
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.hikari.maximum-pool-size=4
spring.datasource.url=jdbc:postgresql://[개발환경IP]:[개발환경PORT]/[개발환경DB명]?characterEncoding=UTF-8&serverTimezone=Asia/Seoul
spring.datasource.username=
spring.datasource.password=
spring.datasource.hikari.schema=
server.servlet.context-path=
server.port=
mybatis.mapper-locations=classpath:mapper/prod/*.xml

 

Profile 구분

spring.config.active.on-profile 은 value의 Profile이 활성화 되었을 때 이하의 설정을 적용한다는 의미이다.

즉,  profile이 local이냐, prod이냐에 따라 연결되는 DB와 Port, server Port 등이 달라진다.

spring.config.active.on-profile 이전에는 spring.profiles.active를 사용하였는데, 2개를 동시에 사용하여 Profile을 활성화 시킬 수 없다.

test=value
spring.profiles.active=prod
#---
spring.config.activate.on-profile=local
test=overridden value
#---
spring.config.activate.on-profile=prod
spring.profiles.active=prod         #--> fail
test=overridden value

그외에 root 수준의 property 속성 정의도 가능하다. 위의 코드에서 최상단 구역의 mybatis 설정들은 모든 property에 동일하게 적용된다.

 

Importing Additional Configuration

추가 속성이나 파일을 가져올 필요가 있을 때 spring.config.import를 사용하여 Profile에 따라 새로운 properties 파일을 불러올 수 있다.

#---
spring.config.activate.on-profile=prod
spring.config.import=prod.properties

import된 prod.properties 파일 내부에는 prod라는 Profile이 활성화 될 때 필요한 환경설정을 작성하면 된다.

 

주의사항

한 파일에 여러 Profile을 작성할 경우, 공통된 설정은 위쪽에 작성하는 것이 좋다.

위에서 설정한 value를 아래에서도 설정하고 있다면 아래쪽의 value가 위쪽의 value를 덮어씌우기 때문이다.

 

여담으로 gradle을 사용해서 Profile이 prod일 때의 jar 파일을 생성할 때, spring.profiles.active=prod를 적지 않고 jar 파일을 생성했더니 테스팅에서는 문제가 없었지만 파일을 실행했을 때는 500 error가 발생했었다. 이러한 점을 봤을 때 코드의 위치가 꽤 중요하다는 걸 알 수 있었다.

 

Profile 활성화 및 프로젝트 실행

IntelliJ에서 프로젝트 실행 시

Run > Edit Configuration에 들어가 Active profiles에 활성화시킬 Profile 명칭을 작성한다.

만일 Active profiles가 없다면 Modify options에서 찾아 추가하면 된다.

프로젝트 실행시

Build 파일 생성 시 Profile 활성화

Gradle을 사용하여 배포용 jar 파일을 생성할 때 어떤 profile의 환경설정을 사용하여 build를 할지 설정할 때는 Run > Edit Configuration > Gradle > build에 들어가 VM option을 작성하면 된다. VM option이 보이지 않는다면 Modify options에서 선택하여 추가한다.

VM option에 -Dspring.profiles.active={원하는 profile}로 작성하면 원하는 Profile 환경설정의 jar 파일을 생성할 수 있다.

 

프로젝트 테스트

package com.testing.ananlysite;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class AppRunner implements ApplicationRunner {

    private final Environment environment;

    public AppRunner(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void run(ApplicationArguments args) {
        System.out.println("======================다중 프로세스 테스트======================");
        System.out.println("Active profiles: "+ Arrays.toString(environment.getActiveProfiles()));
        System.out.println("Datasource driver: "+environment.getProperty("spring.datasource.driver-class-name"));
        System.out.println("Datasource url: "+environment.getProperty("spring.datasource.url"));
        System.out.println("Datasource username: "+environment.getProperty("spring.datasource.username"));
        System.out.println("Datasource password: "+environment.getProperty("spring.datasource.password"));
        System.out.println("Server Port: "+environment.getProperty("server.port"));
        System.out.println("==============================================================");
    }
}

 

local 테스트

 

prod 테스트


[ 참고 ]

https://www.baeldung.com/spring-profiles

https://colabear754.tistory.com/112

https://newwisdom.tistory.com/89

https://ksh-coding.tistory.com/98

https://data-make.tistory.com/722

https://www.blog.ecsimsw.com/entry/Multi-document-Properties-Files-with-Spring-Boot-24