Programming/Springboot
[spring] @value null
bisi
2020. 3. 26. 14:49
|| 현상
@Value 어노테이션으로 application.properties에 설정한 값을 가지고 오려고 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package com.example.demo;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class TestConstruct {
@Value("${testlog.name}")
private static String testString;
@PostConstruct
public static void printString(){
System.out.println("testString : " + testString);
}
public static void main(String[] args) {
printString();
}
}
|
application.properties에 입력하고 결과 확인했더니.. Null...! 해결방법은 아래와 같다.
application.properties
결과
1
2
3
4
|
testString : null
Process finished with exit code 0
|
|| 해결방법
1. 원인 : 문제는 변수의 static 선언
- 스프링에서는 정적변수로 선언된 변수에는 injection 할수 없다.(참고)
2. 해결
- static 선언을 포기
- static을 사용하고 싶다면 @Component, @Service 어노테이션을 선언하고 @Autowired로 선언하여 사용한다.
Component 어노테이션 사용 예