1.自定义事件类
package com.test.event;
import org.springframework.context.ApplicationEvent;
/**
* 自定义事件
* 继承 org.springframework.context.ApplicationEvent
*/
public class MyEvent extends ApplicationEvent {
/**
* Constructs a prototypical Event.
*
* @param source The object on which the Event initially occurred.
* @throws IllegalArgumentException if source is null.
*/
public MyEvent(Object source) {
super(source);
}
}
2.通过事件传递的数据(不需要传递数据时,可以不用)
package com.test.event;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* 定义事件原内容
* 这个可有可无,用于测试通过事件传递数据
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyEventSource {
private Date date;
private String message;
}
3.监听自定义事件
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
/**
* 项目启动事件监听
* @author
* @since $$Id$$
*/
@Component
public class StartUpListener {
//ApplicationStartedEvent.class 应用启动完成事件
@EventListener(ApplicationStartedEvent.class)
public void startSuccess(){
System.out.println("项目启动完成");
}
//ApplicationFailedEvent.class 应用启动失败事件
@EventListener(ApplicationFailedEvent.class)
public void startFaild(){
System.out.println("项目启动失败");
}
//监听自定义的事件,并获取数据原
@EventListener(MyEvent.class)
public void listen(MyEvent event){
MyEventSource source = (MyEventSource) event.getSource();
System.out.println(source.getDate()+" "+source.getMessage());
}
}
4.测试方法(创建,公布事件)
package com.test.controller;
import com.test.event.MyEvent;
import com.test.event.MyEventSource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* 测试接口
*
*/
@RestController
public class TestRest {
@Resource
ApplicationEventPublisher publisher;
@GetMapping("/test/event")
public String testEvent(){
//创建事件,如果不需要传递数据,可以给new Object()
//MyEvent myEvent = new MyEvent(new Object());
//如果需要传递数据,可以给任意数据对象,因为MyEvent构造器的参数为Object
MyEvent myEvent = new MyEvent(new MyEventSource(new Date(), "是谁?"));
//公布事件,公布之后才能监听到
publisher.publishEvent(myEvent);
return "请查看控制台";
}
}