近段时间使用微信Web版的API,实现一个微信机器人, 想每天早上像微信群发送天气预报, 在创建定时任务的时候,发现抛出异常,断点发现是在定时任务里获取不到ChatroomDescriptionService 这个service, 在网上查了查,发现需要手动去配置一个类,主动获取实例来解决这个问题。
首先创建一个工具类:
package com.cherry.jeeves.utils;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;/** * @className: ApplicationContextUtil * @Description: 解决定时任务获取不到service的问题 * @Author moneylee * @Date 2019-05-11 14:28 * @Version 1.0 **/@Componentpublic class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextUtil.applicationContext = applicationContext; } public static Object getBean(String beanName) { return applicationContext.getBean(beanName); }}复制代码
在serivice上添加注解 @Service("chatroomDescriptionService")
package com.cherry.jeeves.service.Impl;import org.springframework.stereotype.Service;import java.util.Map;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.cherry.jeeves.dao.ChatroomDescriptionDao;import com.cherry.jeeves.entity.ChatroomDescriptionEntity;import com.cherry.jeeves.service.ChatroomDescriptionService;@Service("chatroomDescriptionService")public class ChatroomDescriptionServiceImpl extends ServiceImplimplements ChatroomDescriptionService {}复制代码
在定时任务类中获取该service
ChatroomDescriptionService chatroomDescriptionService = (ChatroomDescriptionService) ApplicationContextUtil.getBean("chatroomDescriptionService");复制代码
参考文章: