실무에서 보통 개발 환경별로 application profile을 분리한다.
현재 회사에서 사내망(dev, stg, prod), 사외망(dev, stg, prod)에서 각각의 yml로 설정을 분리하는 방식을 사용했다.
기능이 추가될수록 yml 파일은 커지고 누군가는 똑같이 맞추기 위해서 그대로 설정을 다른 yml에 붙여넣으면서 배보다 배꼽이 더 커지는 것을 보고 배꼽을 눌러주기 위해 profile 분리에 대해 공부하고 적용했다.
환경
- MACBOOK AIR M1
- Intellij ultimate
- spring boot 2.7
- maven3
- jdk17
기본적으로 local 환경에서 구동할 경우 어떤 환경으로 서버를 구동할지에 대한 설정이 필요하기 때문에 profiles.active
혹은 profiles.default
를 명시해야 한다.
물론, profile이 없거나 찾지 못하는 경우 spring은 자동으로 기본 설정 파일인 application.yml or application.properties를 읽어 들인다.
spring boot 2.4 이전
서비스가 조금 오래되었다면 다음과 같이 profile 설정을 할 수 있다.
#application.yml
spring:
profiles:
active: local # local로 기본 profile 지정한다.
# default profile의 값, profile 설정이 없거나 찾지 못하면 해당 값을 읽음
greeting: global-hello
--- # profile 구분자
spring:
profiles: local # application-local.yml과 같음
greeting: local-hello
spring:
profiles: dev
greeting: dev-hello
혹은 한 파일에서 제어하지 않고, 아래처럼 각각의 환경을 위한 파일을 만들고, post-fix에 환경명을 추가해주는 방법도 있다.
공통적으로 사용되는 설정은 다음과 같이 포함시킬 수 있다.
spring:
profiles: dev
include:
- common # common 설정을 포함한다.
greeting: dev-hello
---
spring:
profiles: common
greeting: common-hello
prefix-before-greeting: hey!
common에 greeting이라는 메타데이터가 있어도 덮어씌지 않는다.
spring boot 2.4 이후
spring boot 2.4 이후부터는 키워드가 조금 달라졌다.
spring.config.activate.on-profiles
로 profile 설정 네이밍이 조금 더 명시적으로 변경되었다.
profiles가 난무했기 때문에 혼란을 야기하는 일을 제거한 것 같다.
다음의 코드를 보며 이해해보자.
spring:
profiles:
active: local # 변경없음. 기본 활성된 profile은 local, 없다면 profile 블록이 아닌 전역에 있는 메타데이터를 읽음
---
spring:
config:
activate:
on-profile: local # profile 정의, application-local.yml과 같음
greeting: hello
그리고 profile에 대한 전체적인 관리를 profiles
에서 group
으로 관리할 수 있게 되었다.
spring:
profiles:
default: local
group:
local: // local환경에서 common과 grouping
- common
dev: // dev환경에서 common과 grouping
- common
---
spring:
config:
activate:
on-profile: local
greeting: hello
---
spring:
config:
activate:
on-profile: dev
greeting: dev-hello
---
spring:
config:
activate:
on-profile: common
greeting:
prefix: hey!
위처럼 profiles
에서 중앙관리식 난방 관리자같은 느낌으로 profile들을 관리할 수 있다.
만약 파일별로 더 깔끔하게 분리를 하고 싶다면 --- 구분자별로 파일을 만들어도 된다.
# application.yml
spring:
profiles:
default: local
group:
local:
- common
dev:
- common
---
spring:
config:
activate:
on-profile: local
greeting: local-hello
yml과 properties를 같이 쓰는 것을 지양하자. 만약 같은 파일 이름을 가진다면 properties가 yml을 덮어씌운다.
'Spring' 카테고리의 다른 글
엔티티 매핑 (0) | 2022.11.18 |
---|---|
영속성 컨텍스트 (0) | 2022.11.18 |
JPA 사용해보기 (0) | 2022.11.15 |
Unit test naming convention (0) | 2022.11.15 |
Tomcat과 Spring의 상호작용 (0) | 2022.11.15 |