@Value 는 간편하지만, 설정이 많아질수록 복잡하고 유지보수에 불리해짐.
이럴 땐 @ConstructorBinding 과 @ConfigurationProperties 를 사용하여 설정값을 객체 단위로 구조화하여 관리하는 것이 바람직함.
@ConfigurationProperties + @ConstructorBinding을 활용한 설정 관리
@ConfigurationProperties 는 Spring Boot에서 외부 설정 파일(application.yml 등)의 값을 Java 객체로 바인딩하는 어노테이션임.
여기에 @ConstructorBinding 을 함께 사용하면 불변성(immutability) 과 IDE 자동완성, 타입 안전성, 테스트 용이성 등을 모두 만족할 수 있음.
1. 기존 방식: @Value 방식의 한계
custom:
title: "나의 앱"
timeout: 5000
@Value("${custom.title}")
private String title;
@Value("${custom.timeout}")
private int timeout;
- 값이 많아질수록 흩어짐, 반복적이고 관리 어려움
- 타입 오류, 오타 확인 어려움
- 리팩토링/자동완성 불리함
2. 개선 방식: @ConfigurationProperties + @ConstructorBinding 사용
① 설정 파일 (application.yml)
app:
name: "my-application"
timeout: 3000
endpoints:
- /api/v1/users
- /api/v1/orders
② 설정 클래스 정의
@ConfigurationProperties(prefix = "app")
@ConstructorBinding
public class AppProperties {
private final String name;
private final int timeout;
private final List<String> endpoints;
public AppProperties(String name, int timeout, List<String> endpoints) {
this.name = name;
this.timeout = timeout;
this.endpoints = endpoints;
}
public String getName() { return name; }
public int getTimeout() { return timeout; }
public List<String> getEndpoints() { return endpoints; }
}
✅ 불변 객체 + 생성자 주입 기반으로 구성되어 안정성과 테스트성이 높아짐
③ 설정 클래스 Bean 등록
@Configuration
@EnableConfigurationProperties(AppProperties.class)
public class AppConfig {
}
Spring Boot 2.2+ 부터는 @SpringBootApplication 이 있을 경우
@EnableConfigurationProperties 없이도 자동 등록되나, 명시하면 명확함
④ 사용 예시
@Component
public class SampleService {
private final AppProperties properties;
public SampleService(AppProperties properties) {
this.properties = properties;
}
public void printInfo() {
System.out.println("앱 이름: " + properties.getName());
System.out.println("타임아웃: " + properties.getTimeout());
System.out.println("엔드포인트: " + properties.getEndpoints());
}
}
3. 장점 요약
항목 | 설명 |
타입 안전성 | 잘못된 타입 바인딩은 컴파일 또는 실행 시 에러 발생 |
불변성 보장 | 생성자 기반으로 값 주입 → 객체가 변경 불가능함 |
자동완성 지원 | IDE에서 설정 key 자동완성 가능 |
재사용 용이 | 여러 컴포넌트에서 설정 객체 주입하여 활용 가능 |
테스트 용이 | @TestConfiguration 등으로 쉽게 Mock 주입 가능 |
4. 주의사항
항목 | 설명 |
Bean 등록 필요 | @EnableConfigurationProperties 또는 @Component 필요 |
spring-boot-configuration-processor 의존성 필요 | IDE 자동완성과 문서화를 위해 필수 |
@ConstructorBinding 은 생성자 단 하나만 지원 | 여러 생성자 불가, @Autowired 불필요 |
<!-- build.gradle 또는 pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
정리
@Value 는 간단한 설정값 주입에 적합하지만, 설정 항목이 많고 구조화가 필요한 경우
@ConstructorBinding + @ConfigurationProperties 조합이 더욱 안전하고 유지보수에 유리함.
생성자 기반으로 불변 객체를 만들고, 설정값을 타입 안정성 있게 주입하여
대규모 프로젝트에서 설정 관리를 체계적으로 구성할 수 있음.
출처 : ChatGPT
'BE > Spring & Spring Boot' 카테고리의 다른 글
@Value (0) | 2025.05.21 |
---|---|
@ElementCollection (0) | 2025.05.20 |
[Spring Boot] HttpClient (0) | 2025.05.12 |
[Spring Boot] 웹소켓 하트비트 (0) | 2025.05.07 |
[Spring Boot] PRG 패턴 (1) | 2025.05.06 |