SpringBoot-事件监听

SpringBoot中实现事件的监听,可以方便的实现同步和异步对监听事件进行处理。

1、首先,需要定义监听的事件

import org.springframework.context.ApplicationEvent;

public class MyApplicationEvent extends ApplicationEvent {

    private static final long serialVersionUID = 1L;

    EventDto eventDto;

    public MyApplicationEvent(Object source, EventDto eventDto) {
        super(source);
        this.eventDto = eventDto;
    }

    public EventDto getEventDto() {
        return eventDto;
    }

    public void setEventDto(EventDto eventDto) {
        this.eventDto = eventDto;
    }
}

2、定义监听器,实现监听器接口的方法,监听器需要加入Spring容器进行管理,可以使用@Component注解,或在入口类中通过context对象添加到容器中。 (这里使用的异步调用,需要在方法onApplicationEvent上添加@Async注解,并在入口类中开启异步请求:@EnableAsync)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Async
    public void onApplicationEvent(MyApplicationEvent event) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("接收到事件,时间为:" + df.format(new Date()));
    }

}

3、在需要的位置将事件发布出去,等待被监听到

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

@Component
public class EventPublisher {
    @Autowired
    ApplicationContext applicationContext;

    public void publish(MyApplicationEvent event) {
        applicationContext.publishEvent(event);
    }
}

4、注册事件

publisher.publish(new MyApplicationEvent(this, eventDto));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值