“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”
Definition:
The Observer pattern is a behavioral design pattern that allows you to define a subscription mechanism to notify multiple other objects that “observe” an object when an event occurs on that object.
Practical requirements:
After the consumer leaves a message in the system, the system administrator needs to be notified by the information in the system station and the administrator needs to be notified by email
Code:
Message entity class: CustomerLeaveMessage. Java
public class CustomerLeaveMessage implements Serializable { private static final long serialVersionUID = 1L; private String id; Private String name; // Private String phone; Private String email; // Contact email private String content; }Copy the code
Create a new Event, inherit ApplicationEvent and pass a CustomerLeaveMessage parameter to the business logic:
/ * * * @ the author frequently the wind * * consumer message events @ the date 2021-07-16 14:26 * / public class CustomerLeaveMessageEvent extends ApplicationEvent { public CustomerLeaveMessageEvent(CustomerLeaveMessage source) { super(source); }}Copy the code
At this point, there are two ways to implement the listener: one is to implement the ApplicationListener interface, and the other is to implement the annotation using @EventListener
-
Implement the ApplicationListener interface
/ * * * listening CustomerLeaveMessageEvent logic * @ the author frequently after the wind * @ the date comes to 2021-07-16 * / @ Slf4j @ Service public class CustomerLeaveMessageEventService implements ApplicationListener < CustomerLeaveMessageEvent > {/ * * * after execution monitoring logic * @ param CustomerLeaveMessageEvent * / @ Override @ Async / / asynchronous public void onApplicationEvent (customerLeaveMessageEvent CustomerLeaveMessageEvent) {log. The info (" user comments after logical response, on-site notice sending to an administrator: {} ", customerLeaveMessageEvent. The toString ()); }}Copy the code
-
This is done by annotating @eventListener.
@Service @Slf4j public class CustomerLeaveMessageEventListener { @EventListener public void SendEmail (CustomerLeaveMessageEvent event) {the info (" sends E-mail to the administrator "); }}Copy the code
Finally use in service:
(1) Inject ApplicationContext
@Autowired
private ApplicationContext applicationContext;
Copy the code
(2) Then append the statement to the logic behind the customer message
applicationContext.publishEvent(new CustomerLeaveMessageEvent(customerLeaveMessage));
Copy the code