ApplicationListener系列文章
简单使用范例
数据对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DemoInfo implements Serializable {
private Integer id;
private String name;
@Override
public String toString() {
return "DemoInfo{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
事件
public class DemoEvent extends ApplicationEvent {
public DemoEvent(DemoInfo source) {
super(source);
}
public DemoInfo getSource() {
return (DemoInfo) super.getSource();
}
}
监听器
public class DemoEventListener implements ApplicationListener<DemoEvent> {
@Override
public void onApplicationEvent(DemoEvent event) {
DemoInfo source = event.getSource();
System.out.println("demo event listener source:" + source.toString());
}
}
发布事件
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
//扫描监听器
applicationContext.register(DemoEventListener.class);
//启动容器
applicationContext.refresh();
//发布事件
applicationContext.publishEvent(new DemoEvent(new DemoInfo(1, "demo")));
}
输出结果
demo event listener source:DemoInfo{id=1, name=‘demo’}
进阶版
上述已经可以正常使用ApplicationListener,但是谁还没有点追求,进阶版:ApplicationListener进阶版