问题:springmvc给静态变量注入报:@Autowired annotation is not supported on static fields
原因:spring annotation不支持静态变量注入
解决:
方法一:把get,set方法的static修饰符去掉,然后在set方法上面加@Autowired即可
public class EnDecryptionServiceImpl implements IEnDecryptionService{ /** 阿里云OSS配置查询 */ private static OSSConfMapper ossConfMapper; /** 阿里云OSS图片上传 */ private static UploadImgOSS uploadImgOSS; public OSSConfMapper getOssConfMapper() { return ossConfMapper; } @Autowired public void setOssConfMapper(OSSConfMapper ossConfMapper) { UploadUtil.ossConfMapper = ossConfMapper; } public UploadImgOSS getUploadImgOSS() { return uploadImgOSS; } @Autowired public void setUploadImgOSS(UploadImgOSS uploadImgOSS) { UploadUtil.uploadImgOSS = uploadImgOSS; } }
方法二:在构造函数上加上@Autowired
/** * 第二种解决 Autowired annotation is not supported on static fields的方式 */ @Autowired public void EnDecryptionServiceTwoImpl(OSSConfMapper ossConfMapper,UploadImgOSS uploadImgOSS) { ossConfMapper=ossConfMapper; uploadImgOSS=uploadImgOSS; log.info(xxx); init(); }
Spring静态注入的三种方式
- xml方式
适合基于XML配置的WEB项目
<bean id="mongoFileOperationUtil" class="com.*.*.MongoFileOperationUtil" init-method="init"> <property name="dsForRW" ref="dsForRW"/> </bean>
@PostConstruct方式
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 注解定义容器销毁之前的所做的操作)
这种方式和在xml中配置 init-method和 destory-method方法差不多,定义spring 容器在初始化bean 和容器销毁之前的所做的操作
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注解;