![](/img/trans.png)
[英]Spring @Autowired annotation doesn't work in Java TimerTask
[英]Spring @autowired annotation with java TimerTask doesn't work
自動裝配注釋在Java計時器任務中不起作用。 請找到我的代碼並提供解決方案。
public class MailScheduleTimer extends TimerTask{
@Autowired
MailService mailService;
@Autowired
UserAccountRepository userAccountRepository;
Logger logger = Logger.getLogger(MailScheduleTimer.class);
@Override
public void run() {
try {
List<UserAccount> userAccounts = userAccountRepository
.getUserAccounts();
for (UserAccount userAccount : userAccounts) {
if (userAccount.getUserRole().getName()
.equals(RolesConstant.USER_ROLE)
&& userAccount.getMailStatus().equals("N")) {
mailService.sendMail(userAccount.getName(),
userAccount.getUserId(), "profile",
userAccount.getName());
userAccount.setMailStatus("Y");
userAccountRepository.saveAndFlush(userAccount);
}
}
} catch (Exception e) {
logger.error("Unable to Send Mail..." + e);
}
}
}
將此代碼添加到您的spring beans配置文件中
<context:component-scan basePackage="Your base package name"/>
<context:annotation-config/>
通過將@Component添加到MailScheduleTimer類中,只需使MailScheduleTimer成為bean:
@Component
public class MailScheduleTimer extends TimerTask{
@Autowired
MailService mailService;
@Autowired
UserAccountRepository userAccountRepository;
Logger logger = Logger.getLogger(MailScheduleTimer.class);
@Override
public void run() {
try {
List<UserAccount> userAccounts = userAccountRepository
.getUserAccounts();
for (UserAccount userAccount : userAccounts) {
if (userAccount.getUserRole().getName()
.equals(RolesConstant.USER_ROLE)
&& userAccount.getMailStatus().equals("N")) {
mailService.sendMail(userAccount.getName(),
userAccount.getUserId(), "profile",
userAccount.getName());
userAccount.setMailStatus("Y");
userAccountRepository.saveAndFlush(userAccount);
}
}
} catch (Exception e) {
logger.error("Unable to Send Mail..." + e);
}
}
}
誰應該調用run方法? 可能是您需要使用@PostConstruct對其進行注釋或實現InitializingBean接口
順便說說。 保留@Component標簽以及它們在其他答案中告訴您的軟件包掃描。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.