本文主要是介绍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 {@EventListenerpublic 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 {@Overridepublic void afterPropertiesSet() {// Publish the custom eventeventPublisher.publishEvent("Hello, world!");}
}
这篇关于Spring 观察者模式 EventListener的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!