IntroductionWe always need do something asynchronized, for example, send an email to user after created. event system is the best way to do it, but we don't want add Subject and Observer interface to our POJO implementation. Refer to Seam, we decide to use annotation to add subject and observer to POJO. DetailsIn UserService, we add a method which delegating to UserRepository to add a new user, such as: public interface UserService {
@Delegator(bean = "userRepository", value = "save")
@RaiseEvent(value = "user.added")
UserDto addUser(UserDto user);
}The magic part is @RaiseEvent("user.added"), this annotation tell system raise domain event "user.added" before and after invoking addUser method. How to observe this event? Let's send an email after this method: interface IUserMailer {
@Observer(value = "user.added", async = true)
void sendMail(UserDto user);
}@Observer has a property when which default value is AFTER, so this annotation tell system observe "user.added" event after invoking, and execute method sendMail asynchronized. All parameters in method which raising event will pass to method which observing this event. Then you just need add a spring bean which implemented IUserMailer. System will take care others.
|