####本篇文章主要介绍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));
}
}
以上全部是同步效果 让我们看一下测试结果吧
如何开启异步呢?其实很简单只需要在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());
}
}
让我看看开启异步后执行的结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。