Develop event-driven Applications using Spring Events
5 min read
SpringBoot : 2.7.5 Java : 11
Overview
This article describes how to remove dependencies using Spring events. When developing an application, dependencies may occur between different services.

User registration
When registering a user, dependencies on EmailService and PostService are created as shown in the figure above.
These dependencies can cause a number of problems, some of which are:
- Strong coupling Maintenance may be difficult because the user registration service is mixed with various logics other than the user registration logic.
- Transaction It’s not a good idea to roll back registration results just because an email failed to send.
I would change the structure of the picture above to the following using Spring events.

UserService creates an event and passes it to ApplicationEventPublisher. When an event is published, ApplicationContext notifies the beans that implement ApplicationListener.
You can see that the dependencies between services are gone.
After explaining the basic example, let’s refactor it into more extensible code.
Briefly describe the service
When a user completes registration, send a welcome email and create a default post.
save user Info → send Email → create default post
GitHub - Seonggil-Jeong/SpringBoot-Sample
Create Event Class
@Getter
public class CreatedAccountEvent {
private String userId;
private String userName;
@Builder
public CreatedAccountEvent(String userId, String userName) {
this.userId = userId;
this.userName = userName;
}
}
It contains the necessary data. Event classes are named in the past tense.
EventsPublisher
@Slf4j
@Component
@RequiredArgsConstructor
public class EventsPublisher {
private final ApplicationEventPublisher applicationEventPublisher;
public void pushCreateUserEvent(final String userId, final String userName) {
log.info(this.getClass().getName() + ".push create user event start!");
log.info("userId : " + userId);
log.info("userName : " + userName);
applicationEventPublisher.publishEvent(CreatedAccountEvent.builder()
.userName(userName)
.userId(userId).build());
}
}
This implements a publisher that sends the events we created. We can send an event using the publishEvent method.
EventsListener
@Slf4j
@Component
@RequiredArgsConstructor
public class EventsListener {
private final PostRepository postRepository;
private final AccountRepository accountRepository;
@EventListener
public void pushEmailListener(CreateAccountEvent event) {
log.info(this.getClass().getName() + ".pushEmailListener Start");
log.info("userId : " + event.getUserId());
log.info("userName : " + event.getUserName());
System.out.println("push Email To " + event.getUserName() + " Hello!");
}
@EventListener
@Transactional(rollbackFor = Exception.class)
public void createDefaultPost(CreateAccountEvent event) {
final AccountEntity account = accountRepository.findById(event.getUserId()).orElseThrow(()
-> new NoSuchElementException("cannot found account with id : " + event.getUserId()));
postRepository.save(PostEntity.builder()
.createDate(new Date())
.postContent("default Post")
.postTitle("Default Post from Listener")
.createUserId(account).build());
}
}
Listeners with matching parameters are executed using the @EventListener annotation.
Service
@Override
public void registerAccount(final RegisterAccountRequest request) throws Exception {
validateService.canRegister(request); // userId, nickname are duplicated
final AccountEntity result = accountRepository.save(AccountEntity.builder()
.userId(request.getUserId())
.password(passwordEncoder.encode(request.getPassword()))
.nickname(request.getNickname())
.userName(request.getUserName())
.createDate(new Date())
.role(RoleType.USER)
.state(1).build());
// remove send email
// remove create default post
eventPublisher.pushCreateUserEvent(result.getUserId(), result.getUserName());
}
Now, you can change the existing service logic and send the event after completing registration.

result of pushEmailListener Method

result of createDefaultPost Method
You can see that these two listeners receive requests and process them normally.
Take it to the next level with extends
Now that you have learned how to use the basics, let’s implement a more flexible Event through inheritance (extends).
It’s like grouping events.
As an example, let’s say that an event is published when a user logs in successfully, and an event is published when a user registers as before.
In this situation, how do we add a listener that is executed when an event for the user occurs? → In a simple way, you can issue additional events in the user login method and the user register method.
// register
public void registerAccount(final RegisterAccountRequest request) throws Exception {
...
eventPublisher.pushCreateUserEvent(result.getUserId(), result.getUserName());
// add eventPublisher.pushUserAction( ~~~ )
}
// login
public void userLogin() {
...
eventPublisher.pushLoginUserEvent(result.getUserId(), result.getUserName());
// add eventPublisher.pushUserAction( ~~~ )
}
But if this method is used, a lot of difficulties arise in maintenance when the service grows. So we can solve this problem by extending.
Class structure

Class structure
As above, accountLoginListener is executed when login is completed, and pushEmailListener and createDefaultPostListener are executed when membership registration is completed. The important thing here is that the listener is executed depending on the type of the parameter.
Therefore, when an event that inherits AccountEvent is executed, a listener that receives AccountEvent as a parameter can be executed.
Based on this, let’s change it to save logs when account (user) related events occur.
abstract class Event
@Getter
@ToString
public abstract class Event {
private final UUID eventId;
private final LocalDate createAt;
public Event(LocalDate createAt) {
this.eventId = UUID.randomUUID();
this.createAt = createAt;
}
}
abstract class AccountEvent extends Event
@Getter
public abstract class AccountEvent extends Event {
private final EventType eventType;
public AccountEvent(LocalDate createAt, EventType eventType) {
super(createAt);
this.eventType = eventType;
}
}
final class CreateAccountEvent extends AccountEvent
@Getter
public final class CreateAccountEvent extends AccountEvent {
private final String userId;
private final String userName;
@Builder
public CreateAccountEvent(LocalDate createAt, EventType eventType, String userId, String userName) {
super(createAt, eventType);
this.userId = userId;
this.userName = userName;
}
}
final class LoginAccountEvent extends AccountEvent
@Getter
public final class LoginAccountEvent extends AccountEvent {
private final String userId;
private final String userRole;
@Builder
public LoginAccountEvent(LocalDate createAt, EventType eventType, String userId, String userRole) {
super(createAt, eventType);
this.userId = userId;
this.userRole = userRole;
}
}
class AccountEventPublisher
The publisher has not changed from the previous one.
@Slf4j
@RequiredArgsConstructor
@Component
public class AccountEventPublisher {
private final ApplicationEventPublisher publisher;
public void pushCreateUserEvent(final String userId, final String userName) {
log.info(this.getClass().getName() + ".push create user event start!");
log.info("userId : " + userId);
log.info("userName : " + userName);
publisher.publishEvent(CreateAccountEvent.builder()
.userName(userName)
.userId(userId)
.createAt(LocalDate.now())
.eventType(EventType.CREATE).build());
}
public void pushLoginUserEvent(final String userId, final String userRole) {
log.info(this.getClass().getName() + ".push login user event Start!");
log.info("userId : " + userId);
log.info("userRole : " + userRole);
publisher.publishEvent(LoginAccountEvent.builder()
.userId(userId)
.createAt(LocalDate.now())
.eventType(EventType.USER_LOGIN)
.userRole(userRole).build());
}
}
class AccountEventListener
@Slf4j
@Component
@RequiredArgsConstructor
public class AccountEventListener {
private final AccountRepository accountRepository;
private final PostRepository postRepository;
private final EventRepository eventRepository;
@EventListener // when createAccount
public void pushEmailListener(CreateAccountEvent event) {
log.info(this.getClass().getName() + ".pushEmailListener Start");
log.info("userId : " + event.getUserId());
log.info("userName : " + event.getUserName());
System.out.println("push Email To " + event.getUserName() + " Hello!");
}
@EventListener // when createAccount
@Transactional(rollbackFor = Exception.class)
public void createDefaultPost(CreateAccountEvent event) {
final AccountEntity account = accountRepository.findById(event.getUserId()).orElseThrow(()
-> new NoSuchElementException("cannot found account with id : " + event.getUserId()));
postRepository.save(PostEntity.builder()
.createDate(new Date())
.postContent("default Post")
.postTitle("Default Post from Listener")
.createUserId(account).build());
}
@EventListener // when login success
public void checkAccountLogin(LoginAccountEvent event) {
log.info(this.getClass().getName() + ".user Login Completed");
log.info("userId : " + event.getUserId());
log.info("userRole : " + event.getUserRole());
}
}
This implements a method that is executed when CreateAccountEvent occurs and a method that is executed when LoginAccountEvent occurs.
Finally, implement a method that receives the parent class AccountEvent as a parameter. This method saves the event content to the DB.
class AccountEventLoggingListener
@Slf4j
@Component
@RequiredArgsConstructor
public class AccountEventLoggingListener {
private final EventRepository eventRepository;
@EventListener
public void loggingAccountEvent(AccountEvent event) {
log.info(this.getClass().getName() + ".account event logging Start!");
eventRepository.save(EventEntity.builder()
.eventId(event.getEventId())
.eventType(event.getEventType())
.eventEntity("ACCOUNT_EVENT").build());
}
}
Now, if you check the results, you can see that the methods appropriate for each event are executed during login and user registration, and that the logging method is always executed.
Result of user registration

Account Table

Post Table

Event_Log Table
Result of user login

checkAccountLogin Method

Event_Log Table
Of course, you can use AOP for this.