目录
SpringBoot 定时任务内 使用@Autowired注入Service 获取不到的问题

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

首先创建一个工具类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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”)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 {

}

在定时任务类中获取该service

1
ChatroomDescriptionService chatroomDescriptionService = (ChatroomDescriptionService) ApplicationContextUtil.getBean("chatroomDescriptionService");

参考文章: https://www.cnblogs.com/doudou2018/p/10416043.html

文章作者: 李财
文章链接: http://moneylee.cn/2019/10/06/SpringBoot%20%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E5%86%85%20%E4%BD%BF%E7%94%A8@Autowired%E6%B3%A8%E5%85%A5Service%20%E8%8E%B7%E5%8F%96%E4%B8%8D%E5%88%B0%E7%9A%84%E9%97%AE%E9%A2%98/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 MoneyLee’s Blog
打赏
  • 微信
  • 支付宝

评论