spring给 类的静态属性注入的方法
1.第一种基于xml 定义Bean的方式
xml代码:

java代码:
public class MongoFileOperationUtil {
private static AdvancedDatastore dsForRW;
private static MongoFileOperationUtil mongoFileOperationUtil;
public void init() {
mongoFileOperationUtil =this;
mongoFileOperationUtil.dsForRW =this.dsForRW;
}
}
2. 第二种 @PostConstruct方式实现
@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 注解定义容器销毁之前的所做的操作)
这种方式和在xml中配置 init-method和 destory-method方法差不多,定义spring 容器在初始化bean 和容器销毁之前的所做的操作;
3. set方法上添加@Autowired注解,类定义上添加@Component注解
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方法注入;
然后注意:成员变量上不需要再添加@Autowired注解
4. 通过 ApplicationContext 对象

定义 配置 Bean 对象

静态配置类初始化 配置类

在 任何地方使用配置,不管是不是静态变量
