import com.qcloud.cos.COSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 全局静态变量
* Created by Steve on 2018/10/13 0013.
*/
@Component
public class GlobalValue {
public static String outFilePath;
public static CloudStorageConfig cloudStorageConfig;
public static COSClient cosClient;
@Autowired
private void setCosClient(COSClient cosClient) {
this.cosClient = cosClient;
}
@Autowired
private void setCloudStorageConfig(CloudStorageConfig cloudStorageConfig) {
this.cloudStorageConfig = cloudStorageConfig;
}
@Value("${app.out.filePath}")
private void setDatabase(String outFilePath) {
this.outFilePath = outFilePath;
}
}
Spring静态注入的四种方式:
(说明:MongoFileOperationUtil是自己封装的一个Mongodb文件读写工具类,里面需要依赖AdvancedDatastore对象实例,dsForRW用来获取Mongodb数据源)
在springframework里,我们不能@Autowired一个静态变量,使之成为一个spring bean,例如下面这种方式:
@Autowired
private static AdvancedDatastore dsForRW;
可以试一下,dsForRW在这种状态下不能够被依赖注入,会抛出运行时异常java.lang.NullPointerException,为什么呢?静态变量/类变量不是对象的属性,而是一个类的属性,spring则是基于对象层面上的依赖注入。
但是自己比较喜欢封装工具类,并通过@Component注解成功能组件,但是功能组件中的方法一般都是静态方法,静态方法只能调用静态成员变量,于是就有