【问题标题】:Spring annotations / ways to document spring custom eventsSpring注解/记录spring自定义事件的方法
【发布时间】:2020-10-13 12:15:06
【问题描述】:
我正在开发一个大型 Spring Boot 应用程序,分为不同的服务。
随着应用程序变得越来越大,我开始看到服务之间存在一些深度耦合,因此我在应用程序的某些部分使用 Spring Events(ApplicationEvent) 实现了一个基本的 Pub/Sub 模型以减少耦合。
每个服务创建和发布自定义事件,其他服务订阅它们想要消费的事件。
我想记录每个服务发布和订阅的事件,以帮助提高可读性和调试。
是否有任何特定的弹簧注释/方法可以帮助完成这项任务?
【问题讨论】:
标签:
java
spring
spring-boot
kotlin
【解决方案1】:
我不知道具体的注释,但我通常做的是有一个sealed class 来保存我的活动,这样我就可以确保所有活动都驻留在一个地方:
sealed class MyEvent(source: Any, name: String) : ApplicationEvent(source) {
data class SomeEvent(val source: Any, val name: String) : MyEvent(source, name)
// ...
}
然后你可以在监听器上使用注解:
@Component
class SomeListener {
@EventListener(condition = "#event.name eq 'hey'")
fun handleConditionalListener(event: SomeEvent) {
// handle event
}
}
这有助于可撤销性,因为您只需要查找 @EventListeners。
您还可以有一个事件侦听器来侦听所有事件,然后您可以根据在那里收集的信息绘制图表。
【解决方案2】:
通常我们只使用 javadoc 来编写此类文档。您可以在服务的方法中这样做:
/**
* @param idFilial to be fetched
* @return Filial object in case there is a return in the search, otherwise an Optional.empty ()
* @implNote Search for a specific Filial from an id
* */
Optional <Filial> findById(Long idFilial);