You can also create your own listeners in Spring. For example whenever a new role is added to the system, you would want to publish a custom event and have a custom listener listent to this and say log them (or) send an email.
Steps to do this.
1. Create a custom event.
2. Create a custom event listener handling that event.
3. Trigger (or) publish the event when something happens.
1. Create a custom event.
Thats it. Now whenever a new role is added, you will get a message in the console as below.
Create a custom event :-)
Steps to do this.
1. Create a custom event.
2. Create a custom event listener handling that event.
3. Trigger (or) publish the event when something happens.
1. Create a custom event.
public class UserEvent extends ApplicationEvent { private AppRole appRole; public UserEvent(Object source, AppRole appRole) { super(source); this.appRole = appRole; } public AppRole getAppRole() { return appRole; } }
2. Create a custom event listener handling that event.
@Componentpublic class UserEventListener { Logger logger = Logger.getLogger(UserEventListener.class); @EventListener public void handleAppRoleListener(UserEvent userEvent) { logger.info("User event listener: " + userEvent.getAppRole().getName()); } }
3. Trigger (or) publish the event when something happens.
@Autowiredprivate ApplicationEventPublisher applicationEventPublisher;
@Transactionalpublic AppRole save(@RequestBody AppRole appAppRole) { roleRepository.save(appAppRole); logger.info("App role info modified : " + appAppRole); applicationEventPublisher.publishEvent(new UserEvent(this, appAppRole)); return appAppRole; }
Thats it. Now whenever a new role is added, you will get a message in the console as below.
2018-02-24 01:11:54.375 INFO 51885 --- [nio-8080-exec-1] cs.trk.user.util.UserEventListener : User event listener: User
2018-02-24 01:11:54.433 INFO 51885 --- [nio-8080-exec-1] cs.trk.user.util.AppListener : -- Request Handled at : Sat Feb 24 01:11:54 CST 2018
Create a custom event :-)
No comments:
Post a Comment