使用ApplicationListener监听使方法仅在项目启动时执行一次

使用场景

springCloud项目ApplicationListener 监听某个方法仅在启动时执行一次
业务中需要某个方法仅在启动时执行一次。
在一些业务场景中,当容器初始化完成之后,需要处理一些操作,比如一些数据的加载、初始化缓存、特定任务的注册等等。这个时候我们就可以使用Spring提供的ApplicationListener来进行操作。

用法

本文以在Spring boot下的使用为例来进行说明。首先,需要实现ApplicationListener接口并实现onApplicationEvent方法。把需要处理的操作放在onApplicationEvent中进行处理:

contextRefreshedEvent.getApplicationContext().getParent() == null

这样其他容器的初始化就会直接返回,而父容器(Parent为null的容器)启动时将会执行相应的业务操作。

关联知识

在spring中InitializingBean接口也提供了类似的功能,只不过它进行操作的时机是在所有bean都被实例化之后才进行调用。根据不同的业务场景和需求,可选择不同的方案来实现。

package com.dawn.service;

import com.dawn.dao.NewsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger logger = LoggerFactory.getLogger(SearchReceive.class);
    @Autowired
    private NewsMapper newsMapper;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次
            //需要执行的方法
            int total = newsMapper.countTotal();
            List list = newsMapper.getNews();
            logger.info("只执行一次的方法:{}", total);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_32332777/article/details/103364076
今日推荐