springboot有时获取配置文件的数据一直为null,前今天才遇到这个问题。,总结一下原因可能如下:
1.类上未加@Component,或@Configuration 或 @Service 或者 @RestController 注解
2 语法错误 如下 错误的写法
@Value("
b
d
.
s
e
c
r
e
t
K
e
y
"
)
p
r
i
v
a
t
e
s
t
a
t
i
c
S
t
r
i
n
g
s
e
c
r
e
t
K
e
y
;
@
V
a
l
u
e
(
"
{bd.secretKey}") private static String secretKey; @Value("
bd.secretKey")privatestaticStringsecretKey;@Value("{bd.secretKey}")
private final String secretKey;
正确的写法:
@Value("
b
d
.
s
e
c
r
e
t
K
e
y
"
)
p
r
i
v
a
t
e
S
t
r
i
n
g
s
e
c
r
e
t
K
e
y
;
@
V
a
l
u
e
(
"
{bd.secretKey}") private String secretKey; @Value("
bd.secretKey")privateStringsecretKey;@Value("{bd.secretKey}")
String secretKey;
3 有时候为啦测试,直接写啦一个main 方法 测试,这种情况下是肯定获取不到的。
4 对象必须使用@Autowired注入,才能正常使用@Value注解,(而不是new 的对象)
当然还有其他的情况,这里就不记录啦,希望这次踩坑记录的对你有所帮助