gpt4 book ai didi

java - spring TaskExecutor 类中的 Autowiring 对象为空

转载 作者:行者123 更新时间:2023-11-30 07:01:39 25 4
gpt4 key购买 nike

我正在尝试使用 Spring TaskExecutor 使用不同的线程运行一个方法。我有一个 Autowiring 的依赖项,我得到一个 NullPointerException 。 Autowiring 的依赖项为空。请帮忙。

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));
}
}

在 Controller 中,我正在创建 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);

最佳答案

@Autowired 注解只能在 Spring bean 类中工作。因此,您必须将您的类声明为 Spring bean,或者通过正确注释它(@Component、@Service、@Repository、@Controller)或者通过在 Spring XML 上下文文件中定义这个 bean。

您也不能自己创建 Spring bean 的实例,而是使用 @Autowired 注释。

关于java - spring TaskExecutor 类中的 Autowiring 对象为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29726819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com