The event-driven pattern (also called event-driven architecture, or EDA) is a software design pattern where components communicate and respond to each other through events rather than direct calls.
Instead of one component explicitly invoking methods on another, it emits an event (a signal that something happened), and other components that are interested in that event can listen and react.
2. Key Components in Event-Driven IoC
- Event Publisher: Component that triggers an event (sends a signal).
- Event Listener / Subscriber: Component that reacts to an event.
- Event Bus / Dispatcher: The framework component that manages subscriptions and dispatches events to listeners.
3. Example in Java (Spring Framework)
Spring provides ApplicationEvent
and ApplicationListener
to implement event-driven IoC.
Step 1: Define an Event
import org.springframework.context.ApplicationEvent;
public class UserRegisteredEvent extends ApplicationEvent {
private String username;
public UserRegisteredEvent(Object source, String username) {
super(source);
this.username = username;
}
public String getUsername() {
return username;
}
}
Step 2: Create an Event Listener
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class WelcomeEmailListener implements ApplicationListener<UserRegisteredEvent> {
@Override
public void onApplicationEvent(UserRegisteredEvent event) {
System.out.println("Sending welcome email to " + event.getUsername());
}
}
Step 3: Publish the Event
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private ApplicationEventPublisher publisher;
public void registerUser(String username) {
System.out.println("Registering user: " + username);
// Publish the event after registration
publisher.publishEvent(new UserRegisteredEvent(this, username));
}
}
Step 4: Run the Application
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class EventDemoApplication implements CommandLineRunner {
private final UserService userService;
public EventDemoApplication(UserService userService) {
this.userService = userService;
}
public static void main(String[] args) {
SpringApplication.run(EventDemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
userService.registerUser("Alice");
}
}
Output:
Registering user: Alice
Sending welcome email to Alice
4. Benefits of Event-Driven IoC
- Loose coupling: Publishers don’t need to know about subscribers.
- Extensibility: Add new listeners without modifying existing code.
- Asynchronous handling: Can easily handle events asynchronously for scalability.