Created
April 19, 2017 04:26
-
-
Save mattrasband/a36cf9bedce9fe39338e2641694e3502 to your computer and use it in GitHub Desktop.
Example of Spring 4.2's @TransactionalEventListener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
@Slf4j | |
public class UserService { | |
private final ApplicationEventPublisher applicationEventPublisher; | |
private final UserRepository userRepository; | |
UserService(ApplicationEventPublisher applicationEventPublisher, | |
UserRepository userRepository) { | |
this.applicationEventPublisher = applicationEventPublisher; | |
this.userRepository = userRepository; | |
} | |
@Transactional | |
public User registerUser(User user) { | |
this.applicationEventPublisher.publishEvent(new UserCreatedEvent(user)); | |
return this.userRepository.save(user); | |
} | |
// tl;dr: the event listener is bound to the @Transactional annotation. Assuming the transaction gets to | |
// the phase your listener cares about (the default is AFTER_COMMIT), the event listener is called. | |
@TransactionalEventListener | |
void onUserRegistered(CreationEvent<User> creationEvent) { | |
log.debug("New user {} created, generating and sending confirmation email.", creationEvent.getObject().getId()); | |
System.out.printf("User created: %s\n", creationEvent.getObject()); | |
log.debug("Email sent to user {}", creationEvent.getObject().getId()); | |
} | |
public abstract class CreationEvent<T> { | |
private final T object; | |
CreationEvent(T object) { | |
this.object = object; | |
} | |
public T getObject() { | |
return object; | |
} | |
} | |
public class UserCreatedEvent extends CreationEvent<User >{ | |
public UserCreatedEvent(User user) { | |
super(user); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment