定义事件
需要继承ApplicationEvent类,相当于安装了一个没有通电,没有灯光的信号灯,需要具有信号灯的基本特征。
package springTest5;
import org.springframework.context.ApplicationEvent;
public class EventTest extends ApplicationEvent {
private static final long serialVersionUID = 1L;
private String message;
public EventTest(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
创建监听类
相当于行人(不管是否使用交通工具),需要实现ApplicationListener接口,并且重写onApplicationEvent方法,可以理解成这个行人需要看信号灯,并且能理解信号灯的意思才行。否则不看信号灯跟没有信号灯没有区别,看了不理解也没用。
package springTest5;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class ListenerTest1 implements ApplicationListener<EventTest> {
public void onApplicationEvent(EventTest event) {
System.out.println("test1:" + event.getMessage());
}
}
注册事件
那么第三步自然是需要一个控制信号灯变化的东西,相当于是给他接好电线,给他一个正常变换红黄绿的程序和电路。
package springTest5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class EventPbulish {
@Autowired
ApplicationContext context;
public void publish(String message) {
context.publishEvent(new EventTest(this, message));
}
}