我正在尝试使用Spring TaskExecutor运行使用不同线程的方法。我有一个autowired dependecy,我得到一个NullPointerException。自动连接的依赖项为null。请帮助。
TaskExecutor类如下:
public class WebClientTaskExecutor {
@Autowired
WebClientService webClientService;
public class SyncMails implements Runnable {
private String userName;
private Store store;
public SyncMails(String userName, Store store) {
this.userName = userName;
this.store = store;
}
@Override
public void run() {
try {
System.out.println("inside sync mails run method");
String[] folderNames = { "inbox", "sent", "trash", "drafts" };
for (String folderName : folderNames) {
//Null pointer exception in below line.webClientservice=null
int messageCount = WebClientTaskExecutor.this.webClientService.getMessageCount(
folderName, this.store);
int dbLatestMessageNumber = WebClientTaskExecutor.this.webClientService
.getLatestMessageNumberFromDb(folderName,
this.userName, 1);
System.out.println("MEssage count---->" + messageCount);
System.out.println("Latest message count dao--->"
+ dbLatestMessageNumber);
if (messageCount > dbLatestMessageNumber) {
WebClientTaskExecutor.this.webClientService.getMailsFromImap(folderName,
messageCount, dbLatestMessageNumber + 1,
this.store, this.userName);
}
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUserName() {
return userName;
}
public void setUser(String userName) {
this.userName = userName;
}
public Store getStore() {
return store;
}
public void setStore(Store store) {
this.store = store;
}
}
private TaskExecutor taskExecutor;
public WebClientTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void syncMails(String userName,Store store){
System.out.println("web client service object---->" + webClientService);
this.taskExecutor.execute(new SyncMails(userName, store));
}
}
在控制器中,我正在创建thrTaskExecutor对象并将其提供给WebClientTaskExecutor构造函数。并启动syncMails方法。
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(50);
executor.initialize();
WebClientTaskExecutor taskExecutor = new WebClientTaskExecutor(executor);
taskExecutor.syncMails(userName, store);
答案 0 :(得分:4)
@Autowired
注释仅适用于Spring bean的类。因此,您必须通过正确地注释它(@Component, @Service, @Repository, @Controller
)或在Spring XML上下文文件中定义此bean,将您的类声明为Spring bean。
您也不能自己创建Spring bean的实例,而是使用@Autowired
注释。