@Value("${custom.property}")
private String value;
장점
단점
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이 어렵기까지 하다.
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) {}
}
장점
단점
@Validated
@ConfigurationProperties(prefix = "custom")
public class CustomProperties {
@NotNull
private Service serviceA;
// ...
}
위와 같은 예시대로 빈 검증이 가능하다.
@Autowired
private Environment env;
String value = env.getProperty("custom.property");
장점
단점
@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 객체와 함께 사용하면 테스트 중 동적으로 설정값을 조회하거나 특정 테스트 케이스에 맞는 설정을 주입할 수 있다.