Spring容器初始化完成后执行指定任务

本文介绍如何在Spring框架中使用定时任务和监听器,包括创建定时任务、实现ApplicationContextAware接口获取Spring容器对象,以及实现ApplicationListener监听器进行容器初始化后的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 创建定时任务

@Component("monitorTask")
@Scope("prototype")
public class MonitorTask extends TimerTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(MonitorTask.class);

    @Override
    public void run() {
        LOGGER.debug("开始检查竞拍商品....");
        ProductService productService = ApplicationContextProvider.getBean(ProductService.class);
        AuctionInfoService auctionInfoService = ApplicationContextProvider.getBean( AuctionInfoService.class);
        OrderService orderService = ApplicationContextProvider.getBean(OrderService.class);
        LOGGER.debug("productService" + productService.toString());
        LOGGER.debug("auctionInfoService" + auctionInfoService.toString());
        LOGGER.debug("orderService" + orderService.toString());
        LOGGER.debug("结束检查竞拍商品....");
    }
}

2. 实现ApplicationContextAware接口,用于获得spring容器对象

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext context;

    private ApplicationContextProvider() {
    }


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

    public static <T> T getBean(Class<T> aClass) {
        return context.getBean(aClass);
    }
}

3. 实现ApplicationListener监听器。(关于Spring内置事件,请看:https://blog.youkuaiyun.com/qq_36306640/article/details/90047885

@Component
public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(InstantiationTracingBeanPostProcessor.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug("spring容器初始化完成");
        }

        // 判断根容器为Spring容器,防止出现调用两次的情况(mvc加载也会触发一次)
        if(event.getApplicationContext().getParent() == null) {
            long interval = 10 * 1000; //默认10秒
            //开启线程,注册竞价物品竞价期限检测服务
            LOGGER.debug("注册竞拍商品定时检测任务,间隔时间为" + interval);
            MonitorTask monitorTask = new MonitorTask();
            Timer timer = new Timer();
            timer.schedule(monitorTask, 0, interval);
        }
    }
}

完成。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值