Simply put, observer mode is similar to the relationship between broadcasting station and radio. Multiple radios go to the same radio channel In a real business scenario, this can be the case. After the order is created successfully, the event is published. Then reduce inventory. Send SMS. Call wechat. Call logistics service. Wait for multiple subsequent businesses to listen to the same event.
Define an event.
package com.study.design.observer.spring; import org.springframework.context.ApplicationEvent; /** * Define events */ public class OrderEvent extends ApplicationEvent { public OrderEvent(Object source) { super(source); } }
Define event publisher
package com.study.design.observer.spring; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; import org.springframework.stereotype.Service; // Event publisher. Publish events to spring In the container. @Service public class OrderPublish implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // Obtain spring Container, set to private property. this.applicationContext = applicationContext; } // call spring Container publishing events public void publishEvent(ApplicationEvent event){ applicationContext.publishEvent(event); } }
Publish event in order service
package com.study.design.observer.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Order operation, business pseudo code */ @Service public class OrderService { // Inject event publisher @Autowired private OrderPublish orderPublish; /** * E-commerce - new order */ public void saveOrder() { System.out.println("1, Order created successfully"); // Create events and set parameters OrderEvent orderEvent = new OrderEvent(123456); // Release events orderPublish.publishEvent(orderEvent); } }
SMS monitor service
package com.study.design.observer.spring; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; // Monitor ,Only after an event is published can it be executed @Component public class SmsListener implements ApplicationListener<OrderEvent> { @Override public void onApplicationEvent(OrderEvent event) { // Gets the parameters in the event. System.out.println("event.getSource The value is:"+event.getSource()); // 2---SMS notification System.out.println("2, Call the interface of SMS sending -> Congratulations on the duvet"); } }
In this way, multiple listeners can be created for different business processing. This is the observer model.