@Value注解为什么不能直接为静态变量赋值

问题描述:

@Value("${oss.endpoint}")
private static String endpoint;

说明:oss.endpoint为springboot配置文件application.properties中配置的常量。

在使用endpoint这个成员变量时,取不到值,是空值。

原因:

静态变量(即类变量)是一个类的属性,而不是对象的属性。spring依赖注入是基于对象层面上的。

而且使用静态变量扩大了静态方法的使用范围,静态方法在spring是不推荐使用的,依赖注入的主要目的是让容器去产生一个对象的实例,然后在整个生命周期中使用他们。一旦你使用静态方法,就不再需要去产生这个类的实例,这会让testing变得更加困难,同时你也不能为一个给定的类,依靠注入方式去产生多个具有不同的依赖环境的实例。这种static field是隐含共享的,并且是一种global全局状态,spring同样不推荐这样去做。

解决:

private static String endpoint;
@Value("${oss.endpoint}")
public void setEndpoint(String endpoint) {
FileService.endpoint = endpoint;
}

注意set方法也是非静态的。 
原文链接:https://blog.csdn.net/qq_27127145/article/details/88863702

posted @ 2020-04-18 11:49  你猜lovlife  阅读(587)  评论(0)    收藏  举报