- 首先创建需要监听的事件类
import org.springframework.context.ApplicationEvent;
public class GoodsEvent extends ApplicationEvent {
private static final long serialVersionUID=-4745768546266023205L;
private String desc = "这是监听器";
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public GoodsEvent(Object source, String desc) {
super(source);
this.desc= desc;
}
}
2.创建监听类
@Component
public class GoodsListener implements Serializable{
public static final long serialVersionUID = 3072098993210509725L;
@EventListener//或者implements ApplicationListener<GoodsEvent>
@Async//支持异步
public void execute(GoodsEvent event) throws Exception {
Thread.sleep(5000);
System.out.println("------------------11111111"+event.getDesc()); //------------------11111111这是监听器;
}
}
3.创建触发监听的类
@Component("goods_service")
public class GoodsService {
public void executeGoodsData() throws Exception {
//因为采用了异步注解
SpringContextUtil.getApplicationContext().publishEvent(new GoodsEvent(this,"54321"));
System.out.println("------------------22222222") //此处先打印
}
}
}
}