秒懂SpringBoot之Spring Events全解析
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEvent;
// 自定义事件,继承自ApplicationEvent
public class CustomEvent extends ApplicationEvent {
private String message;
public CustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
// 事件监听器,实现ApplicationListener接口
public class CustomEventListener implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent event) {
System.out.println("接收到CustomEvent:" + event.getMessage());
}
}
// 在SpringBoot应用中使用ApplicationEventPublisher发布事件
@Service
public class CustomEventService {
@Autowired
private ApplicationEventPublisher publisher;
public void publishCustomEvent(String message) {
CustomEvent customEvent = new CustomEvent(this, message);
publisher.publishEvent(customEvent);
}
}
// 在SpringBoot启动类或配置类中注册事件监听器
@Configuration
public class CustomEventConfiguration {
@Bean
public CustomEventListener customEventListener() {
return new CustomEventListener();
}
}
这个代码示例展示了如何在SpringBoot应用中定义、监听和发布自定义事件。首先定义了一个CustomEvent类来表示事件,然后实现了一个CustomEventListener来监听这个事件。在CustomEventService中,我们可以通过注入ApplicationEventPublisher来发布CustomEvent事件。最后,在配置类中注册了CustomEventListener,以确保它能被Spring容器识别并监听事件。
评论已关闭