SpringBoot
SpringBoot 외부 프로퍼티 적용하기(application.yml)
심나라
2023. 12. 6. 14:43
728x90
SpringBoot 외부에 있는 프로퍼티를 적용하는 방법중에서 'spring.config.import' 를 이용하는 방법입니다.
SpringBoot에서 외부 프로퍼티를 적용하는 다양한 방법 아래 가이드를 참고 하세요.
SpringBoot 프로젝트를 실행하면 디폴트로 classpath(src/main/resources)에 있는 application.yml (application-{profile명}.yml) 파일을 프로퍼티 파일로 자동 인식하여 생성이 됩니다.
[spring.config.import 를 이용하여 외부설정파일 적용]
1. application.yml - 기본 설정파일
spring:
primary:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:~/test
username: sa
password:
config:
import: classpath:h2_db_config.yml
classpath 최상위 디렉토리에 있는 h2_db_config.yml 파일 1개 import 하기
2. h2_db_config.yml - 외부설정파일
spring:
secondary:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:~/test
username: sa
password:
3. configTest.java - 외부설정파일을 잘 가져오는지 확인
package com.example.externalConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class configTest {
@Value("${spring.secondary.datasource.driver-class-name}")
private String driverName;
@Value("${spring.secondary.datasource.url}")
private String url;
@Bean
public void configTestMethod() {
System.out.println("driverName : " + driverName);
System.out.println("url : " + url);
}
}
프로그램 실행시 아래 이미지와 같이 외부설정파일의 내용을 출력합니다.
4. spring.config.import를 이용해서 여러개의 프로퍼티 파일 가져오기
spring:
primary:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:~/test
username: sa
password:
config:
import:
- classpath:h2_db_config.yml
- file:C:/test/h2_db_config.yml
- http://localhost:8080/h2_db_config.yml
classpath, file, url 옵션을 이용해서 다양한 방법으로 프로퍼티 파일을 가져올 수 있습니다.
- classpath:h2_db_config.yml : Spring 프로젝트 내부 classpath 경로에 있는 파일을 가져옴.
- file:C:/test/h2_db_config.yml : Spring 프로젝트 외부의 서버 or PC에 있는 파일을 가져옴.
- http://localhost:8080/h2_db_config.yml : URL을 이용해서 파일을 가져옴.
- optional : 파일이 존재하지 않아도 실행에 문제가 되지 않도록 하기 위해서는 optional을 추가함.
- optional:classpath:h2_db_config.yml
- optional:file:C:/test/h2_db_config.yml
- optional:http://localhost:8080/h2_db_config.yml
728x90