1. 创建自定义事件
import org.springframework.context.ApplicationEvent;
import java.util.List;public class CollectionCreateEvent extends ApplicationEvent {private List<String> fileList;public CollectionCreateEvent(Object source,List<String> fileList) {super(source);this.fileList = fileList;}public List<String> getFileList() {return fileList;}
}
2. 创建事件监听器
(1) 实现ApplicationListener接口;
(2) 使用@EventListener注解,@EventListener注解可以直接在方法上使用,以指定该方法为事件监听器。
import java.util.List;@Component
public class DatasetListener {@Autowiredprivate SysFileService fileService;@EventListenerpublic void handleMyEvent(CollectionCreateEvent event) {//处理事件try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}List<String> fileList = event.getFileList();System.out.println(fileList.size());System.out.println(JSON.toJSONString(fileList));System.out.println(fileService);}
}
3. 创建事件发布者
@Component
public class EventPublish {@Autowiredprivate ApplicationEventPublisher publisher;public void publishCreateCollection(List<String> fileList) {CollectionCreateEvent customEvent = new CollectionCreateEvent(this, fileList);publisher.publishEvent(customEvent);}
}
4. 异步监听
监听类加注解 @Async
项目启动类加 @EnableAsync