0
0
Spring Bootframework~10 mins

Event-driven architecture pattern in Spring Boot - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to publish an event using Spring Boot's ApplicationEventPublisher.

Spring Boot
applicationEventPublisher.[1](new CustomEvent(this, "Hello"));
Drag options to blanks, or click blank then click option'
ApublishEvent
BsendEvent
CfireEvent
DraiseEvent
Attempts:
3 left
💡 Hint
Common Mistakes
Using methods like sendEvent or fireEvent which do not exist.
2fill in blank
medium

Complete the code to listen for events using @EventListener annotation.

Spring Boot
@EventListener
public void handleEvent([1] event) {
    System.out.println(event.getMessage());
}
Drag options to blanks, or click blank then click option'
AObject
BCustomEvent
CApplicationEvent
DEvent
Attempts:
3 left
💡 Hint
Common Mistakes
Using generic types like Object or ApplicationEvent which may not match the event.
3fill in blank
hard

Fix the error in the event class by completing the constructor correctly.

Spring Boot
public class CustomEvent extends ApplicationEvent {
    private final String message;

    public CustomEvent(Object source, String message) {
        super([1]);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}
Drag options to blanks, or click blank then click option'
Asource
Bmessage
Cthis
Devent
Attempts:
3 left
💡 Hint
Common Mistakes
Passing message or this instead of source to the superclass constructor.
4fill in blank
hard

Fill both blanks to create a listener method that listens asynchronously and logs the event message.

Spring Boot
@Async
@EventListener
public void onEvent([1] event) {
    logger.[2]("Received: " + event.getMessage());
}
Drag options to blanks, or click blank then click option'
ACustomEvent
Binfo
Cdebug
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong event type or logging level like debug instead of info.
5fill in blank
hard

Fill all three blanks to define a Spring Boot event publisher bean and publish an event inside it.

Spring Boot
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
public class EventPublisher {

    private final ApplicationEventPublisher [1];

    public EventPublisher(ApplicationEventPublisher [2]) {
        this.[3] = [2];
    }

    public void publish(String message) {
        [1].publishEvent(new CustomEvent(this, message));
    }
}
Drag options to blanks, or click blank then click option'
Apublisher
BeventPublisher
CapplicationEventPublisher
DeventPub
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for field and constructor parameter causing confusion.