Unexpected error occurred in scheduled task
时间: 2023-08-08 22:12:22 浏览: 324
回答: 在使用@Scheduled注解进行定时调度时,可能会遇到"Unexpected error occurred in scheduled task"的错误。这个错误通常是由于在服务启动时,@Scheduled注解的执行级别高于spring @Resource资源注入的级别,导致自动注入失败。解决这个问题的办法是创建一个ScheduleConfig类,并实现ApplicationContextAware接口,通过该类获取ApplicationContext,并提供一个静态方法用于获取bean。这样,在定时任务中可以通过该方法获取需要的bean,避免自动注入失败的问题。具体的解决办法如下所示:
@Component
public class ScheduleConfig implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return context != null ? context.getBean(clazz) : null;
}
}
通过以上的解决办法,你可以在定时任务中使用ScheduleConfig.getBean()方法获取需要的bean,避免自动注入失败的问题。
#### 引用[.reference_title]
- *1* [异常 :Unexpected error occurred in scheduled task 。 Spring Boot定时任务调度注解@scheduled](https://blog.csdn.net/UpjQ16/article/details/129757623)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [SpringBoot Task定时任务报错Unexpected error occurred in scheduled task原因及解决办法](https://blog.csdn.net/weixin_63692154/article/details/126274945)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文