一、介绍
监听器的简化写法
二、原理
三、使用
@Slf4j
@Component
public class MyTask {@EventListenerpublic void onApplicationEvent(ApplicationEvent event) {if (event instanceof ContextRefreshedEvent) {log.info("监听到 ContextRefreshedEvent...");}if (event instanceof MyEvent) {log.info("监听到 MyEvent...");MyEvent myEvent = (MyEvent) event;System.out.println("时间:" + myEvent.getTime() + " 信息:" + myEvent.getMsg());}}
}
@Slf4j
@Component
public class MyTask {@EventListenerpublic void MyEventListener(MyEvent event) {log.info("监听到 MyEvent...");MyEvent myEvent = (MyEvent) event;System.out.println("时间:" + myEvent.getTime() + " 信息:" + myEvent.getMsg());}@EventListenerpublic void ContextRefreshedEventListener(MyEvent event) {log.info("监听到 ContextRefreshedEvent...");}
}
还可以指定监听事件的类型:
@EventListener(MyEvent.class)@EventListener({MyEvent.class, ContextRefreshedEvent.class})
四、demo
在前面的基础上,改造listener的写法:
package com.listener.demo.listener;import com.listener.demo.dto.UserLogDTO;
import com.listener.demo.event.MyLogEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class MyListener {@EventListenerpublic void onApplicationEvent(MyLogEvent event) {UserLogDTO source = event.getSource();log.info("监听到:url={},detail={}",source.getUrl(),source.getDetail());//其他处理,比如存储日志}
}
访问localhost:4444/listenerDemo/user/add?userName=zhangsan&userAccount=zs,控制台也同样打印