프로그래밍 이야기/SPRING BOOT 공부

스프링부트 설정파일

글쓰는 개발자 김뉴네 2023. 9. 25. 21:38
728x90
반응형

- 애플리케이션 실행시 application.properties 설정파일 읽어들이는 위치 순서

1> 현재 디렉토리의 /config 서브 디렉토리

2> 현재 디렉토리

3> 클래스 경로의 /config패키지

4> 클래스 경로의 루트

 


- 설정파일은  프로파일이라는 단위로 별도의 설정을 가지며 개발환경, 프로덕션환경 등 환경별로 설정을 나누고 싶은 경우에는 application-{profile}.properties의 명명 규칙으로 설정 파일을 만든다.

- 설정파일의 작성형식은 YAML로도 가능하며 YAML 형식의 설정을 사용하려면 application.properties 대신에 application.yml 파일을 배치하면 자동 로드 된다.


- 속성형식 설정

  foo.remote-address = 127.0.0.1

  foo.security.username = kimnew

 

- YAML 형식 설정

  foo:

     remote-address : 128.1.1.1

  security:

     username : kimnew

 


@ConfigurationProperties 사용하여 프로그램에서 설정값 사용하기

@Component
@ConfigurationProperties(prefix="foo")
@Validated
public class SomePojo {
@NotNull
InetAddress remoteAddress;

@Valid
Security security = new Security();

public static vlass Security{
@NotEmpty
String username

// getter  setters
}
}


@Validated 어노테이션을 작성하면 빈 검증으로 속성값을 체크한다. 제약조건을 위한반 값이 설정되면 어플리케이션 실행 시 예외가 발생하므로 설정이 빠져 있거나 설정이 틀린것을 바로 발견할 수 있다.

@ConfigurationProperties 어노테이션을 이용하면 느슨한 바인딩이 이뤄지기 때문에 클래스의 변수와 설정 파일의 키가 정확하게 일치하지 않아도 느슨하게 바인딩 된다.

@Value를 사용하여 프로그램에서 설정값 사용하기

@Component
public class SomePojo{
@Value("${foo.remote-address}")
String remoteAddress;

@Value("${foo.security.username}")
String securityUserName;
}

 

728x90
반응형