티스토리 뷰

Spring

외부 설정 - 1부

kingsubin 2020. 7. 7. 15:35

외부 설정 파일

- 애플리케이션에서 사용하는 여러가지 설정 값들을 애플리케이션의 밖이나 안에 정의할 수 있는 기능이다.

 

사용할 수 있는 외부 설정

- properties
- YAML
환경변수
커맨드 라인 아규먼트

 

application.properties는 기본적으로 key-value값이고,

스프링 부트가 애플리케이션을 구동할 때 자동으로 로딩하는 파일이다.

 

 

외부설정을 사용하는 방법

- application.properties에 입력한 값을 @Value로 사용 가능하다.

- Environment 객체를 가져와 .getProperty("key) 메서드로 사용 가능하다.

 

테스트에서의 외부 설정

- 테스트 실행시 main -> test 순서로 프로젝트를 빌드,
test 에 있는 파일들이 main 에 있는 파일들을 오버라이딩한다.
즉, main 과 test 에 동일하게 application.properties 가 있다면, test 내의 application.properties 가 최종적으로 사용된다.
따라서, 테스트 환경에서 main 과 다르게 별도의 설정을 주어야 하는 경우 주의가 필요하다.
이를 위해 테스트 파일에서 외부 설정을 다르게 주는 방법은 다음과 같다.

 

- @SpringBootTest 의 Properties 속성
@SpringBootTest(properties = "subin.lee = Test")

 

@TestPropertySource 사용

@TestPropertySource(properties = "subin.lee = Test")

 

- 별도의 properties 파일 생성

@TestPropertySource(locations = "classpath:/test.properties")


프로퍼티 랜덤값 사용 ,플레이스 홀더

application.properties에서 ${random.xxx} 으로 랜덤값 사용 가능

 

서버포트는 random값으로 주면 안되고 0으로 줘야함

가용한 포트번호중에 랜덤으로 받음

 


프로퍼티 우선순위

우선 순위를 간략히 정리.

  1. @TestPropertySource
  2. @SpringBootTest(properties=...)
  3. 커맨드 라인 argument
  4. @PropertySource
  5. 기본 프로퍼티

Properteis 파일 우선순위

application.properties  resources/ 말고 다른 곳에서도 사용될 수 있다.
이 때 application.properties 의 위치에 따른 우선 순위는 다음과 같다.

  1. /config/
  2. /
  3. <classpath>/config/
  4. <classpath>/

 

※참조

www.inflearn.com/course/스프링부트/lecture/13535

dailyheumsi.tistory.com/171

 

'Spring' 카테고리의 다른 글

로깅 - 1부, 2부  (0) 2020.07.08
Profile  (0) 2020.07.08
외부설정 - 2부  (0) 2020.07.07
SpringApplication - 2  (0) 2020.07.06
SpringApplication - 1  (0) 2020.07.04