반응형

Spring Boot 에서 Properties 를 설정하는 방법에 대해서 알아보자.


우선 Properties 파일을 3개를 만들어 보았다.

src/main/resources 하위에 application.properties, application-server1.properties, application-server2.properties 이렇게 3개의 파일을 만들었다.


application.properties

1
2
3
4
application-name: my applicatoin
spring.output.ansi.enabled=always
logging.level.org.springframework.web=debug
server.port=9000
cs


application-server1.properties

1
server.port=9001
cs


application-server2.properties

1
server.port=9002
cs


일단 이런 상태로 어플리케이션을 실행 시켜서 CommandLineRunner 로 서버 포트랑 application name 을 찍어보았다.


1
2
c.p.s.SpringPropertiesApplication        : application Name : my applicatoin
c.p.s.SpringPropertiesApplication        : server port : 9000
cs


찍히는 것은 당연히 application.properties 파일에 있는 내용들이 찍혀 나온다.


그럼 이번에는  application.properties  파일에  spring.profiles.active=server1 이라고 입력해보자.


1
2
c.p.s.SpringPropertiesApplication        : application Name : my applicatoin
c.p.s.SpringPropertiesApplication        : server port : 9001
cs


이번에는 application-server1.properties 에 application-name: my applicatoin 9001 이라고 입력해보자.


1
2
c.p.s.SpringPropertiesApplication        : application Name : my applicatoin 9001
c.p.s.SpringPropertiesApplication        : server port : 9001
cs


지금까지 테스트한 결론은 이렇다.


1. properties 의 profile  을 active 안하면 기본적으로 default properties를 읽는다.

2. active 한 properties 는 default properties의 값들을 override 한다.


In addition to application.properties files, profile-specific properties can also be defined by using the following naming convention: application-{profile}.properties. The Environment has a set of default profiles (by default, [default]) that are used if no active profiles are set. In other words, if no profiles are explicitly activated, then properties from application-default.properties are loaded.

Profile-specific properties are loaded from the same locations as standard application.properties, with profile-specific files always overriding the non-specific ones, whether or not the profile-specific files are inside or outside your packaged jar.


spring boot document 에도 위와 같이 나와있다. 마지막 문장을 번역해보면 다음과 같다.


profile-specific properties 는 기본적인 application.properties 파일처럼 같은 위치에서 로드된다. 그리고 profile-specific 파일들은 이 파일들이 패키지된 jar파일 안에 있거나 밖에 있거나 상관 없이 non-specific  파일들을 항상 오버라이딩 한다. 


일단 내가 이 테스트를 통해서 알고 싶었던 것은 이부분이었다. active 한 프로파일이 아예 기존 properties 파일을 교체하는지 아니면 기존 파일에 있는 값들을 유지 하되 중복되는 값들은 override 하는지 알고 싶었다. 결과는 기존값을 유지하고 중복값은 override  한다였다.


프로젝트를 여러군데 배포하다 보면 배포 환경에 따라서 값들이 변경되는 값들 있다. 편하게 관리를 하려면 profile을 나누는게 확실히 도움이 되는데 항상 우선순위 때문에 헷갈렸다. 물론 properties 파일이 외부에 있는 경우, commandline 으로 들어오는 경우등 여러 가지 케이스가 더 있긴 할테지만 우선 이것으로 내 궁금증은 풀렸다.


프로젝트 소스 : https://github.com/blusky10/study_spring



728x90
반응형

+ Recent posts