1. Type-Safe Configuration Properties 소개
@Value("${property}") 어노테이션을 사용한 설정 프로퍼티 주입은 여러 프로퍼티를 다루거나 계층적 데이터 구조를 가진 경우 번거로울 수 있습니다. Spring Boot는 강타입 빈을 통해 애플리케이션 설정을 관리하고 검증할 수 있는 대안적인 방법을 제공합니다.
Type-Safe Configuration의 장점
- 타입 안전성: 컴파일 타임에 타입 오류를 검출할 수 있습니다.
- 구조화된 설정: 관련된 설정들을 하나의 클래스로 그룹화할 수 있습니다.
- IDE 지원: 자동 완성과 설정 메타데이터를 제공합니다.
- 검증 기능: JSR-303 검증 어노테이션을 활용할 수 있습니다.
2. JavaBean Properties Binding
표준 JavaBean 프로퍼티를 선언하는 빈을 바인딩할 수 있습니다.
2.1 기본 예제
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("my.service")
public class MyProperties {
private boolean enabled;
private InetAddress remoteAddress;
private final Security security = new Security();
// getter / setter 메서드들...
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public InetAddress getRemoteAddress() {
return this.remoteAddress;
}
public void setRemoteAddress(InetAddress remoteAddress) {
this.remoteAddress = remoteAddress;
}
public Security getSecurity() {
return this.security;
}
public static class Security {
private String username;
private String password;
private List<String> roles = new ArrayList<>(Collections.singleton("USER"));
// getter / setter 메서드들...
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return this.roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
}
}
2.2 매핑되는 프로퍼티
위의 POJO는 다음 프로퍼티들을 정의합니다:
my.service.enabled- 기본값 falsemy.service.remote-address- String에서 변환 가능한 타입my.service.security.username- 중첩된 "security" 객체my.service.security.passwordmy.service.security.roles- 기본값 USER를 가진 String 컬렉션
바인딩 요구사항
이러한 방식은 기본 빈 생성자와 getter/setter 메서드에 의존합니다. 바인딩은 Spring MVC와 동일하게 표준 Java Beans 프로퍼티 디스크립터를 통해 수행됩니다.
2.3 Setter 생략 가능한 경우
다음 경우에는 setter를 생략할 수 있습니다:
- Map: 초기화되어 있다면 getter만 필요하고 setter는 필수가 아닙니다
- 컬렉션과 배열: 인덱스나 쉼표로 구분된 값으로 접근 가능합니다
- 중첩 POJO: 초기화되어 있다면 setter가 필요하지 않습니다
Lombok 사용 시 주의사항
Project Lombok을 사용하는 경우, 특별한 생성자를 생성하지 않도록 주의하세요. 컨테이너가 객체를 자동으로 인스턴스화할 때 사용됩니다.