I am trying to run a method using different thread using Spring TaskExecutor. I have an autowired dependecy,I am getting a NullPointerException .The autowired dependency is null. Please Help.
The TaskExecutor class is below:
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));
}
}
In controller,I am creating thrTaskExecutor object and giving it to WebClientTaskExecutor constructor.And starting the syncMails method.
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(50);
executor.initialize();
WebClientTaskExecutor taskExecutor = new WebClientTaskExecutor(executor);
taskExecutor.syncMails(userName, store);
The @Autowired annotation will work only in classes that are Spring beans. Therefore, you must declare your class as Spring bean, either by annotating it properly (@Component, @Service, @Repository, @Controller) or by defining this bean in the Spring XML context file.
You must also not create an instance of a Spring bean yourself, but use the @Autowired annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With