在springframework里,我们不能@Autowired一个静态变量,使之成为一个spring bean,例如下面这样:
@Autowired
private static YourClass yourClass;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GlobalValue {
@Value("${mongodb.db}")
public static String DATABASE;
}
如果你获取GlobalValue.DATABASE,会得到null
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
输出:
@Autowired
private static AdvancedDatastore dsForRW;
可以试一下,dsForRW在这种状态下不能够被依赖注入,会抛出运行时异常java.lang.NullPointerException,为什么呢?静态变量/类变量不是对象的属性,而是一个类的属性,spring则是基于对象层面上的依赖注入。
public class MongoFileOperationUtil {
private static AdvancedDatastore dsForRW;
private static MongoFileOperationUtil mongoFileOperationUtil;
public void init() {
mongoFileOperationUtil = this;
mongoFileOperationUtil.dsForRW = this.dsForRW;
}
}
这种方式适合基于XML配置的WEB项目;
import org.mongodb.morphia.AdvancedDatastore;
import org.springframework.beans.factory.annotation.Autowired;
@Component
public class MongoFileOperationUtil {
@Autowired
private static AdvancedDatastore dsForRW;
private static MongoFileOperationUtil mongoFileOperationUtil;
@PostConstruct
public void init() {
mongoFileOperationUtil = this;
mongoFileOperationUtil.dsForRW = this.dsForRW;
}
}
@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;(@PreDestroy 注解定义容器销毁之前的所做的操作)
import org.mongodb.morphia.AdvancedDatastore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MongoFileOperationUtil {
private static AdvancedDatastore dsForRW;
@Autowired
public void setDatastore(AdvancedDatastore dsForRW) {
MongoFileOperationUtil.dsForRW = dsForRW;
}
}
首先Spring要能扫描到AdvancedDatastore的bean,然后通过setter方法注入;