Spring 监听事件Demo

####本篇文章主要介绍spring 监听事件 同步和异步的方法

1:先定义一个事件本身 extends ApplicationEvent类 代码如下:

/**
 * 事件类
 */
@Setter@Getter@ToString
public class IEvent extends ApplicationEvent {
    private Long id;
    private String name;
    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public IEvent(Object source, Long id, String name) {
        super(source);
        this.id=id;
        this.name=name;
    }


  • 2:事件监听类一共有两种
  •    2.1:实现ApplicationListener监听事件类复写onApplicationEvent()方法
    

接下来看列子吧

//这里实现监听注意这里填写自己的事件类 如果不填写默认是监听applicationEvent类
@Component
public class IListener implements ApplicationListener<IEvent> {

   @Override
   public void onApplicationEvent(IEvent event) {
       System.out.println(event.toString()+"监听到的事件");
   }
}
  •   2.2:使用注解@EventListener
    
@Component
public class IListener{



    @EventListener
    public void  onApplicationEvent(IEvent event){
        System.out.println("后台正在生成名字用户ID为:"+event.getId());
        System.out.println("后台正在生成名字:"+event.getName());
    }
}

3:事件发布 可以使用ApplicationContext 上下文对象 发布事件
也可以实现ApplicationEventPublisherAware 发布事件
我比较懒使用ApplicationContext 上下文引用对象发事件

@Service
public class IEventServiceImpl implements IEventService {

    @Resource
    private ApplicationContext context;

    @Override
    public void publisher(Long id,String msg) {
        //这里使用ApplicationContext 上下文应用对象发布时间消息
        context.publishEvent(new IEvent(context,id,msg));
    }
}

以上全部是同步效果 让我们看一下测试结果吧
z在这里插入图片描述
如何开启异步呢?其实很简单只需要在springBoot启动类加载注解即可 @EnableAsync

@SpringBootApplication
@EnableAsync
public class ListenerApplication implements WebMvcConfigurer {
    public static void main(String[] args) {
        SpringApplication.run(ListenerApplication.class,args);
    }
}
@Component
public class IListener{
    @EventListener
    @Async //异步执行注解
    public void  onApplicationEvent(IEvent event){
        System.out.println("后台正在生成名字用户ID为:"+event.getId());
        System.out.println("后台正在生成名字:"+event.getName());
    }
}

让我看看开启异步后执行的结果:
在这里插入图片描述
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值