목차
- 문제
- 원인
- 해결책
- 참고
문제
foo.properties 파일
str.foo = staticValue
java 파일
@Component
public class CommonVariables {
@Value("${str.foo}")
public static String strFoo; //null
}
외부 프로퍼티 파일로부터 @Value를 통해 값을 주입하려했으나 null 발생.
원인
스프링은 @Value를 static field에 지원하지 않는다.
해결책
public static String strFoo;
@Value("${str.foo}")
private void setStrFoo(String strFoo){
CommonVariables.strFoo = strFoo; // "staticValue"
}
- 스프링이 CommonVariables클래스를 초기화
- 초기화 할때 스프링이 우선적으로 @Value 가 붙은 필드나 메서드를 찾음
- 스프링은 @Value가 붙은 메서드에 값을 주입하려 했으나, setter 메서드에게 위임
- setter 메서드가 값을 할당
참고
https://www.baeldung.com/spring-inject-static-field
Injecting a Value in a Static Field in Spring | Baeldung
Learn how to inject a value into a static field in Java
www.baeldung.com
'Programming > Languages (Java, etc)' 카테고리의 다른 글
[JSP] 내장객체 (0) | 2022.11.10 |
---|---|
[JSP] Runtime (0) | 2022.11.02 |
JSP란 (0) | 2022.10.05 |
JAVA는 call by reference 없습니다. (0) | 2022.07.19 |
분할정복 알고리즘 (0) | 2022.06.23 |
댓글