HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
✍🏻
Learnary (learn - diary)
/
🎶
[Core] - 외부 설정 파일에 존재하는 상수 값을 주입하는 방법 (생성자 방식)
🎶

[Core] - 외부 설정 파일에 존재하는 상수 값을 주입하는 방법 (생성자 방식)

progress
Done
Tags
Spring
보통 Java에서 상수 값은 코드적으로 Enum이나 private final static으로 관리를 할 것이다.
하지만 Spring에서는 .properties 나 .yml 확장자 설정 파일들을 관리할 수 있도록 도와준다.
 
이번에는 .properites 또는 .yml 에 있는 값들을 소스 코드에 주입해서 사용하는 방식에 대해 알아보겠다.
 
소스코드에 주입하는 방식은 3가지 있다.
  1. component 등록+ConfigurationProperties + getter + setter 주입 방식
  1. component 등록 + @Value 주입 방식
  1. ConstructBinding + ConfigurationProperties + 외부 클래스에 configuration + EnableConfigurationProperties(${ConstructBinding을 받는 클래스})
 
문제점
  1. 첫번째 방식은 getter 뿐만 아니라 setter도 열려있어 변경에 대한 여지가 열려있게 된다.
  1. 해당 prefix가 중복이 발생한다.
 
결국 2개 모두 불변성에 대해 문제가 있다.
final 한 필드로 인스턴스 변수를 생성할 수 없기 때문이다.

💨What

🌕
final 키워드를 사용하여 최초 초기화를 보장하며 불변을 유지할 수 있는 property 주입 방식

❓Why

  • 불변 객체는 외부에서 가져온다 한들 변경에 대해 막혀 있어 버그 또는 이슈가 발생할 수 있는 여지가 줄어든다.
  • 특히나 생성자 전략은 객체 생성시 최초 초기화 1번을 보장하는 방식이므로 안전하기 때문이다.

✅How

  1. component 등록+ConfigurationProperties + getter + setter 주입 방식
@Component @ConfigurationProperties(prefix = "personal") class TestConfigInjection { private String value; public void setValue(String value) { this.value = value; } public String getValue() { return value; } }
  1. component 등록 + @Value 주입 방식
@Component class PropTestConfig { @Value("${personal.value}") private String value; public String getValue() { return value; } }
  1. ConstructBinding + ConfigurationProperties + 외부 클래스에 configuration + EnableConfigurationProperties(${ConstructBinding을 받는 클래스})
// 선언 방식 @Autowired private CreatorTest ct; @ConstructorBinding @ConfigurationProperties(prefix = "personal") class CreatorTest { private String value; public void setValue(String value) { this.value = value; } public String getValue() { return value; } } @Configuration @EnableConfigurationProperties({CreatorTest.class}) class ConsConfig{ }

📌 REFER

Spring Boot에서 properties 값 주입받기
Spring Boot를 이용해서 어플리케이션을 만들다 보면 외부에서 특정 값들을 주입받아야 하는 경우가 있다. 예를 들면 AWS의 특정 컴포넌트를 사용하기 위한 secret key가 될 수도 있고 외부 API를 사용하기 위한 API key가 될 수도 있다. 이러한 값들을 소스 코드에 하드 코딩한다면 악의적인 의도를 가진 사람이 값을 탈취하여 사용하면서 큰일로 이어질 수 있다.
Spring Boot에서 properties 값 주입받기
https://tecoble.techcourse.co.kr/post/2020-09-29-spring-properties-binding/
Spring Boot에서 properties 값 주입받기
Yaml의 Property를 Class로 바인딩 해보자
yaml 파일의 프로퍼티들을 불러와서 사용하고 싶을 때가 있다. 예를 들어 JWT의 header, 토큰 이름, 유효기간 등등... 어떻게 클래스에 바인딩을 해주는지 알아보자. 제가 사용할 프로퍼티들은 다음과 같이 계층구조를 이루고 있습니다. Security 설정에 관한 프로퍼티들을 하나의 Bean에 바인딩해 사용하고 싶습니다. 설정 중 jwt 부분만 떼어내어 getter setter 방식을 살펴보겠습니다. 최상단 클래스레벨에 @Component와 @ConfigurationProperties 어노테이션을 사용해줍니다.
Yaml의 Property를 Class로 바인딩 해보자
https://velog.io/@pjh612/Property%EB%A5%BC-Class%EB%A1%9C-%EB%A1%9C%EB%94%A9%ED%95%B4%EB%B3%B4%EC%9E%90
Yaml의 Property를 Class로 바인딩 해보자