Spring Boot 외부설정 값 읽는 3가지 방법

Regular Kim·2025년 5월 31일
0

기타

목록 보기
5/19
  1. @Value
  2. @ConfigurationProperties
  3. Environment 객체

@Value

@Value("${custom.property}")
private String value;

장점

  • 간단한 값 주입에 적합 (주로 원시타입)
  • 코드가 간결함

단점

  • 다수의 값을 주입할 때 비효율적
  • IDE에서 자동 완성이나 타입 체크 안 됨
  • 반복적인 코드가 많아질 수 있음

다수의 값을 주입할 때 비효율적?

custom:
  serviceA:
    url: http://a.com
    token: abc123
  serviceB:
    url: http://b.com
    token: def456

설정 파일에 위와 같은 내용이 있다고 가정한다.

@Component
public class ServiceConfig {

    @Value("${custom.serviceA.url}")
    private String serviceAUrl;

    @Value("${custom.serviceA.token}")
    private String serviceAToken;

    @Value("${custom.serviceB.url}")
    private String serviceBUrl;

    @Value("${custom.serviceB.token}")
    private String serviceBToken;

    // getter 생략
}

반복 코드가 많은 구조가 된다. 게다가 만일 key 값이 변한다면 수동으로 바꿔줘야 하며, 테스트시 mocking이 어렵기까지 하다.

@ConfigurationProperties

custom:
  serviceA:
    url: http://a.com
    token: abc123
  serviceB:
    url: http://b.com
    token: def456

이런 복잡한 설정 파일의 값을 사용한다고 가정한다.

@Component // <- 필수! 다른 방법도 있지만 번거로움
@ConfigurationProperties(prefix = "custom")
public record CustomProperties(
    Service serviceA,
    Service serviceB
) {
    public record Service(String url, String token) {}
}

장점

  • 복잡한 설정 파일을 그대로 객체에 바인딩
  • 타입 안전, IDE 자동완성 지원
  • 테스트와 재사용에 유리
  • Validator 적용 가능 (@Validated 사용)
  • Profile 기반 설정 구분 용이

단점

  • record가 아니라면 getter/setter 필요 -> 설정이 많음

Validator 적용 가능?

@Validated 
@ConfigurationProperties(prefix = "custom") 
public class CustomProperties { 

	@NotNull 
	private Service serviceA; 
	// ... 
	
}

위와 같은 예시대로 빈 검증이 가능하다.

Environment 객체

@Autowired
private Environment env;

String value = env.getProperty("custom.property");

장점

  • 동적으로 설정값 조회 가능
  • 주입 시점이 아닌 호출 시점에 값 조회
  • 테스트 유용

단점

  • 타입 안전하지 않음 (항상 String)
  • IDE 자동완성 불가
  • 복잡한 바인딩 불가

테스트에서 어떻게 사용함?

@SpringBootTest
@TestPropertySource(properties = {
    "custom.serviceA.url=http://test.com",
    "custom.serviceA.token=test123"
})
class ServiceConfigTest {

    @Autowired
    private Environment env;

    @Test
    void testEnvironmentProperties() {
        String url = env.getProperty("custom.serviceA.url");
        String token = env.getProperty("custom.serviceA.token");

        assertEquals("http://test.com", url);
        assertEquals("test123", token);
    }
}

@TestPropertySource 는 테스트에서 특정 프로퍼티 소스를 지정해 테스트 환경의 설정값을 오버라이드할 때 유용하다. Environment 객체와 함께 사용하면 테스트 중 동적으로 설정값을 조회하거나 특정 테스트 케이스에 맞는 설정을 주입할 수 있다.

정리

@Value

  • 단순한 원시값 1~2개
  • 단일 키 주입

@ConfigurationProperties

  • 설정이 여러 개이거나 계층 구조

Environment

  • 유틸성 도구/테스트 코드
profile
What doesn't kill you, makes you stronger

0개의 댓글