[Spring] @ConfigurationProperties를 통해 프로퍼티 설정 값 가져오기 (@ConstructorBinding)
@ConfigurationProperties
@ConfigurationProperties를 사용하여 application.yml등과 같은 설정정보에 작성한 설정 값을 가져올 수 있습니다.
간단한 예시를 통해 확인해보겠습니다.
application.yml
myproperty:
name: shin
설정 값을 보관할 클래스
@ConstructorBinding
@ConfigurationProperties("myproperty")
data class ApplicationProperties(
val name: String,
) {
}
@ConstructorBinding을 사용하면 생성자 방식으로 값을 세팅할 수 있어, 불변 객체를 만드는 데 용이합니다.
만약 이를 사용하지 않으면 setter를 통해 값을 바인딩 시켜주어야 하는데, 이렇게 되면 객체의 불변성을 보장할 수 없습니다.
@ConfigurationProperties을 사용하기 위해서는 @ConfigurationPropertiesScan 혹은 @EnableConfigurationProperties를 사용하여야 합니다.
@EnableConfigurationProperties 사용
@EnableConfigurationProperties(ApplicationProperties::class)
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
위와 같이 속성 값을 바인딩 시킬 클래스를 지정해 주어야 합니다.
@ConfigurationPropertiesScan 사용
@ConfigurationPropertiesScan
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
ComponentScan이 동작하는 것 처럼 동작하여, @ConfigurationProperties가 붙은 클래스를 스캔합니다.
Reference
https://mangkyu.tistory.com/189
[SpringBoot] final 변수를 갖는 클래스에 프로퍼티(Properties) 설정 값 불러오기, 생성자 바인딩(Construct
Spring 프레임워크로 개발을 하다 보면 프로퍼티(Properties)에 저장된 특정한 설정 값들을 불러와야 하는 경우가 있다. 많은 글 들에서 프로퍼티(Properties)를 불러오는 내용들을 설명하고 있는데, 이
mangkyu.tistory.com