java发布事件

public class OrderService {

@Autowired
ApplicationContext applicationContext;
public void  saveOrder(){

    //1.创建订单
    System.out.println("1.创建订单成功");
    //发布事件
    OrderInfo orderInfo = new OrderInfo();
    orderInfo.setId(1L);
    applicationContext.publishEvent(new OrderEvent(orderInfo));

//
// //2.发送短信
// System.out.println(“2.发送短信”);
//
//
// //3.发邮件
// System.out.println(“3.发邮件”);
}
}

public class OrderEvent extends ApplicationEvent {
public OrderEvent(OrderInfo source) {
super(source);
}
}

3.public class SmsListener implements ApplicationListener {

@Override
public void onApplicationEvent(OrderEvent orderEvent) {
    //2.发短信
    System.out.println("2.发短信");
}

}
4.
@Component
public class EmailListener implements ApplicationListener {

@Override
public void onApplicationEvent(OrderEvent orderEvent) {
    //2.发短信
    System.out.println("3.发邮件");
}

}
5.
@Component
public class WxListener implements SmartApplicationListener {

@Override
public boolean supportsSourceType(Class sourceType) {
    return sourceType== OrderInfo.class;
}

@Override
public int getOrder() {
    return 0;
}

@Override
public boolean supportsEventType(Class aClass) {
    return aClass == OrderEvent.class;
}

@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
    OrderInfo source =(OrderInfo) applicationEvent.getSource();
    System.out.println("4.发送微信"+source.getId());
}

}

你可能感兴趣的:(springboot,java,开发语言,后端)