jeudi 26 novembre 2020

Best practice to organize SpringBoot Events/EventListeners

I think this is strongly related to Observer and Publish/Subscribe patterns but since I have still not seen production code using it, I have some questions on how you guys organize your code when using events and eventListeners in SpringBoot (though I believe it can be extended to any languages/frameworks).

Let's say I have 3 classes and their respective services :

Foo with FooService
Bar with BarService
Baz with BazService

When FooService creates a Foo object, I want BarService and BazService to execute some code to update their respective tables for exemple so I publish the FooCreatedEvent.

What are the best practices here since I have 2 different services ?

Solution 1 :

One class encapsulating everything

public class FooEventListener {

    @Autowired
    private BarService barService;
    @Autowired
    private BazService bazService;

    @EventListener
    public void handleFooCreatedEvent(FooCreatedEvent event) {
       barService.doSomething(event);
       bazService.doSomething(event);
    }

}

Solution 2 :

2 classes each encapsulating its own service

public class BarEventListener {

    @Autowired
    private BarService barService;

    @EventListener
    public void handleFooCreatedEvent(FooCreatedEvent event) {
       barService.doSomething(event);
    }

}

public class BazEventListener {

    @Autowired
    private BazService bazService;

    @EventListener
    public void handleFooCreatedEvent(FooCreatedEvent event) {
       bazService.doSomething(event);
    }

}

I like solution 2 in terms of design, but I think it can be a bit confusing to have BarEventListener handle FooEvents

What do you guys think ?

Aucun commentaire:

Enregistrer un commentaire