springboot在使用Scheduled做定时任务出现Autowired注入空指针

原因:Scheduled的加载时机要早于Autowired;
解决:通过在ApplicationContext中按名称查找service

mport org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Date20/01/08 12:44
 * @Version V1.0
 **/
@Component
public class ApplicationContextUtil  implements ApplicationContextAware {
    @Autowired
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

此时就不用Autowired注入,要显示的获取

//例如获得redisService 类
  RedisService redisService = (RedisService)ApplicationContextUtil.getBean("redisService");
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是一个使用 `@Scheduled` 注解实现定时任务的 Spring Boot 示例代码: 首先,在 Spring Boot 项目的 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` 然后,在一个 Spring Boot 的 Java 类中添加以下代码: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { @Scheduled(fixedRate = 5000) // 每隔 5 秒执行一次 public void task1() { System.out.println("Task1: " + System.currentTimeMillis()); } @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次 public void task2() { System.out.println("Task2: " + System.currentTimeMillis()); } } ``` 上面代码中,我们使用 `@Scheduled` 注解来实现两个定时任务,一个是每隔 5 秒执行一次,另一个是每分钟执行一次。 其中,`@Scheduled` 注解有两个常用的属性: - `fixedRate`:表示任务执行的间隔时间,单位为毫秒。 - `cron`:表示基于 Cron 表达式的定时任务配置,格式为 `second minute hour dayOfMonth month dayOfWeek year`。 最后,启动 Spring Boot 应用程序,即可看到定时任务在后台自动执行的输出结果。 注意:在 Spring Boot 应用程序中使用 `@Scheduled` 注解时,需要在应用程序主类上添加 `@EnableScheduling` 注解,以启用定时任务功能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值