Spring 观察者模式 EventListener

Step 1: Set up a Spring Boot project

Step 2: Create a custom event (plain java object). implementation with ApplicationEvent (marker class).

public class MyCustomEvent extends ApplicationEvent {

    private String message;

    public MyCustomEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

Step 3: Create an event publisher (spring bean with method). use ApplicationEventPublisher or ApplicationContext.

@Service
public class MyEventPublisher {

    private final ApplicationEventPublisher eventPublisher;

    public MyEventPublisher(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    public void publishEvent(String message) {
        MyCustomEvent event = new MyCustomEvent(this, message);
        eventPublisher.publishEvent(event);
    }
}

Step 4: Create an event listener (spring bean). Annotate a method within this class with the @EventListener annotation, specifying the event type that the method should handle.

@Component
public class MyEventListener {

    @EventListener
    public void handleCustomEvent(MyCustomEvent event) {
        System.out.println("Received custom event: " + event.getMessage());
        // Handle the event logic here
    }
}

Step 5: Test the event handling

@Component
public class DemoComponent implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
        // Publish the custom event
        eventPublisher.publishEvent("Hello, world!");
    }
}

你可能感兴趣的:(spring,观察者模式,java)