본문 바로가기

공부내용 정리/스프링

Spring Boot 2.4 이상 버전의 application.yml 에서 Profile 설정하기

스프링부트 2.4 설정파일 출시 공식문서

https://spring.io/blog/2020/08/14/config-file-processing-in-spring-boot-2-4

 

Config file processing in Spring Boot 2.4

Spring Boot 2.4.0.M2 has just been released, and it brings with it some interesting changes to the way that application.properties and application.yml files are loaded. If your applications use the fairly typical setup of only using a single application.pr

spring.io

 

저는 스케줄러를 하나 만들고 있었는데 설정파일이 로컬/개발/검수/운영서버 별로 달라야 하기 때문에 

손쉽게 할 수있는 방법을 찾아서 테스트해보고 적용해보았습니다.

 

스프링 부트 2.4.x 이상이면 application.yml 에서 profile 별로 설정하여 손쉽게 사용할 수 있습니다.

 

제가 사용한 예시입니다.

dev는 개발, stage는 검수(테스트), prod는 운영이라고 하겠습니다.

spring.profile.group  ->  profile 그룹을 설정합니다.

예를 들어 아래에서는 

"dev" : "dev, common" 

"stage": "stage"

"prod": "prod"

이렇게 설정하여 사용하였는데요

그 아래에 active 가

active: stage 로 되어있는데 만약 "dev" 로 설정하게 되면

프로젝트의 profiles가 "dev"로 설정되고 프로젝트가 application-dev.yml 과 application-common.yml 을 참조하게 됩니다.

그럼 만약 active: prod 로 설정하게 된다면? 

"prod" 그룹에 있는 "prod", 즉 application-prod.yml 을 참조하게 됩니다.

spring:
  profiles:
    group:
      "dev": "dev, common"
      "stage": "stage"
      "prod": "prod"
    active: stage

  altibase:
    datasource:
      driver-class-name: 
      jdbc-url: 
      username: 
      password: 
      mybatis-config: classpath:mybatis/mybatis-config.xml
      mapper-locations: classpath:/mapper/*Mapper.xml

server:
  port: 8081

 

 

이번엔 application-dev.yml 을 살펴보겠습니다.

위에서 active: dev 로 설정해놓았었습니다.

설정은 application.yml 과 비슷하지만

spring.config.active.on-profile: dev 로 되어있습니다.

(application-stage.yml 이라면 spring.config.active.on-profile: stage 입니다.)

아래의 db  설정은 설정한  profiles에 맞는 db정보를 넣어주면 됩니다.

포트도 각각 설정가능하며, 만약 스케줄러를 사용한다면 아래처럼 cron 설정도 각각 해줄 수 있겠죠?

spring:
  config:
    activate:
      on-profile: dev
  altibase:
    datasource:
      driver-class-name: 
      jdbc-url: 
      username: 
      password: 
      mybatis-config: classpath:mybatis/mybatis-config.xml
      mapper-locations: classpath:/mapper/*Mapper.xml

logging:
  config: classpath:log4j2-dev.xml

#server:
#  port: 8082

 

 

application.yml  에서 profiles 를 active: dev로 설정하고 프로젝트를 실행시켜보았습니다.

The following 2 profiles are active: "dev", "common" 가 보이시나요?

application.yml 에서 group 이 "dev" : "dev, common"  로 설정 되어있었습니다.

그렇기때문에 application-dev.yml 과 application-common.yml 을 참조하게 되고,

로그파일도 log4j2-dev.xml 을 참조하게 됩니다.

 

끝~!