Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Spring Framework FAQ: Top Questions

42. How does Spring manage application events?

Spring provides a flexible eventing system to publish and listen to application-level events, using ApplicationEventPublisher and @EventListener.

📘 Steps:

  1. Define a custom event class.
  2. Publish the event using ApplicationEventPublisher.
  3. Handle it using @EventListener.

📥 Example:

public class UserRegisteredEvent extends ApplicationEvent {
  public UserRegisteredEvent(Object source) {
    super(source);
  }
}

@Component
public class UserListener {
  @EventListener
  public void onUserRegister(UserRegisteredEvent event) {
    System.out.println("User registered!");
  }
}

🏆 Expected Output:

Prints "User registered!" when the event is triggered.

🛠️ Use Cases:

  • Triggering async operations post entity actions.
  • Implementing decoupled workflows or notifications.