定时任务代码:
/**
* @Author mxy
* @Date 2021/9/15
* @Desc 用户定时任务
*/
@Slf4j
@Component
public class UserTask {
//注入方式不用@Autowired,改成下面的代码注入
private final IUserInfoService userInfoService= (IUserInfoService) ApplicationContextUtil.getBean("userInfoService");
/**
* 定时任务 一小时一次
*/
@Scheduled(cron = "0 0/60 * * * *")
public void doTask() throws Exception {
userInfoService.queryAll();
// do something
}
}
用户接口类
/**
* @Author mxy
* @DateTime 2021-09-15
* @Desc 用户接口 服务类
*/
public interface IUserInfoService {
List<UserInfo> queryAll();
}
用户接口实现类
/**
* @Author mxy
* @DateTime 2021-09-15
* @Desc 用户接口 实现类
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
//@Bean用于ApplicationContextUtil.getBean("userInfoService")的映射
@Bean
public UserInfoServiceImpl userInfoService(){
return new UserInfoServiceImpl();
}
@Override
public List<UserInfo> queryAll() {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
queryWrapper.select("*");
return baseMapper.selectList(queryWrapper);
}
}
用户实体
/**
* @Author mxy
* @Date 2021-09-15
* @Desc 用户实体类
*/
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="UserInfo", description="用户")
public class UserInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
@ApiModelProperty(value = "用户名称")
private String username;
@ApiModelProperty(value = "用户年龄")
private Integer age;
}
用户mapper
/**
* @Author mxy
* @DateTime 2021-09-15
* @Desc 用户 Mapper 接口
*/
@Mapper
@Repository
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
工具类
/**
* @Author mxy
* @Date 2021/9/15
* @Desc 解决定时任务不能注入mapper和service
*/
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}
注意事项:
ApplicationContextUtil 的代码位置要在task代码之前,启动服务时,代码的顺序,会影响到执行顺序,如果位置不正确,还是会导致service获取空指针
下方是我的目录接口: