SpringBoot 定时任务内 使用@Autowired注入Service 获取不到

近段时间使用微信Web版的API,实现一个微信机器人, 想天天早上像微信群发送天气预报, 在建立定时任务的时候,发现抛出异常,断点发现是在定时任务里获取不到ChatroomDescriptionService 这个service, 在网上查了查,发现须要手动去配置一个类,主动获取实例来解决这个问题。html

首先建立一个工具类:java

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
 **/
@Component
public 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")spring

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 ServiceImpl<ChatroomDescriptionDao, ChatroomDescriptionEntity> implements ChatroomDescriptionService {

}

复制代码

在定时任务类中获取该servicebash

ChatroomDescriptionService chatroomDescriptionService = (ChatroomDescriptionService) ApplicationContextUtil.getBean("chatroomDescriptionService");
复制代码

参考文章:www.cnblogs.com/doudou2018/…微信

相关文章
相关标签/搜索