设计模式-观察者模式 springboot实现
观察者1
@Component
public class MailListener implements ApplicationListener<OrderEvent> {
//private static final Logger logger= Logger.getLogger(SmsListener.class);
//private static final Logger logger = Logger.getLogger(SmsListener.class);
@Override
@Async
public void onApplicationEvent(OrderEvent event){
System.out.println(Thread.currentThread()+"___邮件监听到"+event.getMessage());
}
}
观察者2
@Component
public class SmsListener implements ApplicationListener<OrderEvent> {
//private static final Logger logger= Logger.getLogger(SmsListener.class);
//private static final Logger logger = Logger.getLogger(SmsListener.class);
@Override
@Async
public void onApplicationEvent(OrderEvent event){
System.out.println(Thread.currentThread()+"___短信监听到"+event.getMessage());
}
}
定义事件
public class OrderEvent extends ApplicationEvent {
private String message;
public OrderEvent(Object source,String message){
super(source);
this.message=message;
}
@Override
public Object getSource(){
return super.getSource();
}
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message=message;
}
}
测试方法,发布事假,监听者1.2均监听到事件
public class BaseTestService {
@Autowired
private ApplicationContext applicationContext;
@Test
public void test01(){
OrderEvent order=new OrderEvent(this,"用户下单");
applicationContext.publishEvent(order);
}
}
image.png
网友评论