@Value – Spring에서 설정값 주입에 사용하는 어노테이션
@Value 는 Spring에서 application.properties, application.yml 또는 시스템 환경변수, 커스텀 프로퍼티 등에서 값을 읽어와 주입하기 위한 어노테이션임.
간단한 구성 값이나 상수를 주입할 때 매우 유용하게 사용됨.
1. 기본 사용법
@Value("${server.port}")
private int port;
- @Value("${설정 key}") 형태로 사용하며,
해당 key가 application.properties 또는 application.yml 에 존재해야 함
예시:
# application.yml
custom:
greeting: "안녕하세요"
@Value("${custom.greeting}")
private String greeting;
2. 지원하는 값 타입
타입 | 예시 |
String, int, boolean 등 기본 타입 | @Value("${config.enabled}") |
List, Set | @Value("#{'${config.list}'.split(',')}") |
SpEL (Spring Expression Language) | @Value("#{2 * 3}") → 6 |
default 값 지정 | @Value("${config.timeout:30}") → 없으면 30 |
3. 기본값 설정
설정 값이 없을 경우 기본값을 지정하려면 : 구문을 사용함:
@Value("${config.limit:100}")
private int limit;
→ config.limit 값이 없으면 100을 주입함
4. SpEL(Syntax Expression Language) 활용
@Value("#{1 + 2}")
private int result; // 3
@Value("#{systemProperties['user.home']}")
private String userHome;
@Value("#{T(java.lang.Math).random() * 100}")
private double randomValue;
- #{} 는 SpEL로 해석되어 동적 계산, static 호출 등도 가능함
5. 컬렉션 주입
config:
fruits: apple,banana,grape
@Value("#{'${config.fruits}'.split(',')}")
private List<String> fruits;
6. Bean 외부에서 사용 (Static 변수 등)
Spring Bean이 아닌 곳이나 static 필드에서는 @Value 가 동작하지 않음
→ 이럴 땐 @PostConstruct 또는 Environment 주입 방식 사용 필요
예시:
@Component
public class ConfigHolder {
@Value("${custom.message}")
private String message;
@PostConstruct
public void init() {
StaticHolder.MESSAGE = message;
}
}
7. @ConfigurationProperties 와의 차이
항목 | @Value | @ConfigurationProperties |
목적 | 단일 값 주입 | 묶음 값 바인딩 |
형태 | 간단, 명시적 | 구조화된 설정 |
예시 | @Value("${key}") | @ConfigurationProperties(prefix="my") |
바인딩 대상 | 필드 하나 | 클래스 전체 (POJO) |
자동 완성 | ❌ (IDE 지원 낮음) | ✅ (Lombok, IDE 지원 높음) |
→ 단일 값 주입은 @Value, 설정 객체 전체 바인딩은 @ConfigurationProperties 사용이 적합함
정리
@Value 는 Spring 애플리케이션에서 외부 설정값을 간편하게 주입하기 위한 어노테이션임.
application.yml, 시스템 변수, 기본값, SpEL 연산 등 다양한 형태의 값 주입을 지원하며,
설정이 단순한 경우나 빠르게 값을 주입해야 할 때 매우 유용하게 사용됨.
복잡하거나 구조화된 설정에는 @ConfigurationProperties 가 더 적합함.
출처 : ChatGPT
'BE > Spring & Spring Boot' 카테고리의 다른 글
@ConfigurationProperties, @ConstructorBinding (0) | 2025.05.22 |
---|---|
@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 |