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/…微信

相關文章
相關標籤/搜索