Spring 實現執行緒介面 Runnable 註解注入失敗 @Resource annotation is not supported on static fields
阿新 • • 發佈:2018-11-09
原因就是spring和多執行緒安全的問題,不讓注入
解決方案有以下幾種
一.變數字首加static,生成set方法並加上@Resource,記住把set方法 static 去掉,否則會丟擲 @Resource annotation is not supported on static fields
private static VerificDao verificDao;
@Resource
public void setVerificDao(VerificDao verificDao) {
CheckVoiceVerify.verificDao = verificDao;
}
- 1
- 2
- 3
- 4
- 5
二.根據spring上下文環境獲取bean
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
// Spring應用上下文環境
private static ApplicationContext applicationContext;
/**
* 實現ApplicationContextAware介面的回撥方法,設定上下文環境
*/
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 獲取物件 這裡重寫了bean方法,起主要作用
*/
public static Object getBean(String beanId) throws BeansException {
return applicationContext.getBean(beanId);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
三. 在啟動這個執行緒的時候,在這個執行緒的建構函式中把需要注入的物件傳過去
new Thread(new CheckVoiceVerify(verifyService)).start();