본문 바로가기
SpringBoot/Common

Spring Multi profile 설정(YML)

by BAYABA 2021. 9. 26.
  1. 개인 공부 목적으로 작성한 글입니다.
  2. 아래 출처를 참고하여 작성하였습니다.
  3. 하나의 Spring Boot Profile에 대한 내용은 아래 포스팅을 참고하시면 됩니다.

목차

  1. multi profile YML 설정 방법
  2. 기본 프로필 설정하기
  3. 현재 실행중인 profile 확인 방법
  4. 적용할 profile 선택 방법

1. multi profile YML 설정 방법

  1. 하나의 application.yml에 여러 profile을 사용하려면 spring.config.activate.on-profile 설정을 씁니다.
  • 기존에는 spring.profiles 속성을 사용했지만 Spring Boot 2.4 버전부터 deprecated 되었습니다.
  1. 프로필 구분자로 --- 를 사용합니다.
# application.yml


spring:
  config:
    activate:
      on-profile: default

server:
  port: 8081

app:
  title: default

---

spring:
  config:
    activate:
      on-profile: beta
server:
  port: 8081

app:
  title: beta

---

spring:
  config:
    activate:
      on-profile: production

server:
  port: 8081

app:
  title: production

---

spring:
  config:
    activate:
      on-profile: sandbox

server:
  port: 8081

app:
  title: sandbox

2. 기본 프로필 설정하기

  1. 빌드 시 별도로 profile 옵션을 설정하지 않으면 default 프로필이 적용됩니다.
  2. default 외에 스프링 부트의 기본 프로필을 설정하기 위해서는 시작 클래스를 수정합니다.
  • 아래 코드의 경우 프로필에 대한 설정 정보가 없을 시 sandbox 프로필을 지정합니다.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AdminApiApplication {

    public static void main(String[] args) {

        String profile = System.getProperty("spring.profiles.active");
        if(profile == null) {
            System.setProperty("spring.profiles.active", "sandbox");
        }

        SpringApplication.run(AdminApiApplication.class, args);
    }

}

3. 현재 실행중인 profile 확인 방법

  1. 아래와 같이 @Value 어노테이션으로 확인해보면 현재 활성화된 프로필을 알 수 있습니다.
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("api/health")
@RestController
public class HealthCheckController {

    @Value("${app.title}")
    String appTitle;

    @GetMapping
    public Long getSystemTime() {
        log.info("appTitle: {}", appTitle);
        return System.currentTimeMillis();
    }
}

4. 적용할 profile 선택 방법

4-1. JAR

  1. 사용하는 방법은 profile 를 선택해서 실행하면 됩니다.
$ java -jar myapp.jar --spring.profiles.active=production

4-2. intellij

  1. Run > Edit Configurations... 선택
  2. Spring Boot Application 선택
  3. Active profiles 에서 원하는 profile 명을 입력 후 실행


출처

  1. Spring Boot profile 환경별 설정하기(YAML)
  2. 환경에 맞는 Spring Profile 설정하기

'SpringBoot > Common' 카테고리의 다른 글

인터셉터(Interceptor)  (0) 2021.09.22
필터(Filter)  (0) 2021.09.22
Spring Profiles 설정 방법  (0) 2021.09.13