我需要在我的Runnable Thread下面訪問Spring beans(featureService
和uxService
),但我得到的null
值爲applicationContext
因此我不能在Runnable中獲得Spring bean。我想知道是否可以訪問runnable內的spring bean?如果不是,請給我一個替代方法。在Runnable線程中訪問Spring Bean
我使用Spring 4.0.6
和Java 8
@Component
public class UserMenuUpdateTask implements Runnable, Serializable, ApplicationContextAware {
private static final long serialVersionUID = 3336518785505658027L;
List<User> userNamesList;
FeatureService featureService;
UXService uxService;
private ApplicationContext applicationContext;
public UserMegaMenuUpdateTask() {}
public UserMegaMenuUpdateTask(List<User> userNamesList) {
this.userNamesList = userNamesList;
}
@Override
public void run() {
try {
for (User user : userNamesList) {
featureService = (FeatureService) applicationContext.getBean("featureService");
uxService = (UxService) applicationContext.getBean("uxService");
//.........
}
} catch (BaseApplicationException ex) {
throw new BaseApplicationException(ex);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
我打電話可運行如下
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new UserMenuUpdateTask(activeUsers));
你叫'setApplicationContext()'運行它之前?您應該也可以向我們展示您如何使用Runnable。 –
@JiriTousek'setApplicationContext()'應該在應用程序啓動時被'Spring'容器調用。我已經更新了調用Runnable – RanPaul
的代碼只能在它知道的bean(對象)上。你在你的代碼中創建了一個Spring無法知道的本地實例(Spring實際上並不使用魔法,即使它有時似乎:) –