具有 @EventListener 和 void 方法的 Spring Event

Spring Event with @EventListener and void method

提问人:mimi1907 提问时间:7/25/2022 更新时间:7/25/2022 访问量:1420

问:

我搜索了一段时间,但不知道我错过了什么。

我想在Spring中实现观察者模式,以更新MongoDB中的文档,这将在前端创建通知。

我使用@EventListener注释为通知实现了一个 Service 类(这里不止一个,我只向您展示其中的两个)


    @Service
    @RequiredArgsConstructor
    public class NotificationService {
    
    @EventListener ({ContextStartedEvent.class})
    public void updateNotificationForIdea(String ideaId) {

    //some logic inside the Service classes

        }
    }

    @EventListener ({ContextStartedEvent.class})
    public void createNotificationForNewComment(String ideaId, String creatorId) {
        
    //some logic inside the Service classes

        }
}

我尝试实现该服务,从我想发送通知的地方

@Service
@RequiredArgsConstructor
public class CommentService {

    private final ApplicationEventPublisher eventPublisher;

    public CommentServiceResult createComment(Comment comment, String creatorId) {

        // some logic

eventPublisher.publishEvent(); //here is where I miss something

        return CommentServiceResult.builder()
                .comment(createdComment)
                .resultState(state)
                .build();
    }

我读到我需要类似“EventHelperClass”的东西,并尝试构建它:

public class NotificationEvents extends  ApplicationEvent{

    public NotificationEvents(Object source) {
        super(source);
    }
    
    private void updateNotificationForIdea(String ideaId){
        
    }

    private void createNotificationForNewComment(String ideaId, String creatorId) {
        
    }
}

但我真的不知道如何从这里的 NotificationsService 获取通知(因为它们是无效的,不是简单的字符串消息),以从 CommentService 中启动事件......

我缩短了服务的依赖关系,并删除了内部logik以提高可读性......

Java Spring Events 侦听 器观察者模式

评论


答:

0赞 Marc Stroebel 7/25/2022 #1
eventPublisher.publishEvent(...)

触发一个事件,你需要传递一个事件对象作为参数,例如

public class CustomSpringEvent extends ApplicationEvent {
    private String message;

    public CustomSpringEvent(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

注释的方法将捕获它。@EventListener ({CustomSpringEvent.class})

就您而言:

CommentService 触发 CommentEvent(字段:Comment comment、String creatorId)。

任何带有方法的 Bean

@EventListener ({CommentEvent.class})
void onCommentEvent(CommentEvent event) {
// ....
}

将捕获它并获取事件数据。

https://www.baeldung.com/spring-events

评论

0赞 mimi1907 7/25/2022
我试过了(我之前读过的 baeldung 链接)。您确定 EventListener 和 CommentEvent.class 吗?不应该是 NotificationEvents.class 吗?如何触发 NotificationsService 的众多事件中的一个特定事件?
0赞 Marc Stroebel 7/25/2022
这只是一个示例,随心所欲地命名
0赞 Marc Stroebel 7/25/2022
eventPublisher.publishEvent(new YourEvent(....))触发特定事件