Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Spring Framework FAQ: Top Questions

17. How does Spring handle events and listeners?

Spring has a built-in event publishing mechanism that follows the Observer pattern. Beans can publish and listen to custom or predefined events.

πŸ—ΊοΈ Components:

  • ApplicationEventPublisher to publish events.
  • @EventListener or ApplicationListener to listen for them.

πŸ“₯ Example:

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

@Component
public class MyListener {
  @EventListener
  public void handleEvent(MyEvent event) {
    System.out.println("Handled event: " + event);
  }
}

πŸ† Expected Output:

Custom event is published and handled by listener bean.

πŸ› οΈ Use Cases:

  • Decoupling components via event communication.
  • Triggering background or audit logic upon domain events.