My goal is to collect/publish different types of information from the application. We use Kafka for the event bus. Consider the following sample code.

class UserService {

public User userUpdateService(String username) {

    try {
        userRepo.save(new User(username));
    } catch (Exception e) {

        // this is a direct method call to publish error event in case of error
        publishEvent.asyncPublishUserUpdateErrorEvent(username, e);

        throw new RuntimeException();

    // As the execution reach the last statement, assuming user update success 


As you see, currently I am calling the method in a UserService class to publish the error or success event. I call this method every time a new event needs to be collected and called directly from the code. I know that the ELK stack can be useful in my use case, but that's not an option for me.

One benefit I've seen in this direct method call is that I have more control over what kind of information is to be published. But by using this method I have to change the class, which I think violates many OO principles.

So, in practice, how can this type of task be accomplished? I'm using the Spring Boot framework.

  • Why do you say that ELK stack is not an option for you? Have you tried Kafka? Jan 9, 2021 at 15:41
  • @SebastianSotto the client has very rigid technology specification that's why ELK cannot be used. I am using Kafka to publish event. publishEvent.asyncPublishUserUpdateErrorEvent(username, e); this method that I've mentioned in my sample code actually publish to a kafka topic. My concern is that the way I'm calling a method to publish is that a good practice. Jan 9, 2021 at 16:23

1 Answer 1


If mixing the event publishing code with your other code is an issue for you, it might be an option to apply the decorator pattern.

Instead of directly calling your implementation of the UserService, call another one which has the same signature but which is solely there to first forward the call to UserService and secondly publish the event(s). By doing so you have separated the aspect of event publishing.

This works if your decorating logic (event publishing) can be wrapped around the decorated logic, as in your case.

Usual implementations of the pattern have the property that both classes implement a common interface (here it would contain the update method) and consumers would then use that interface, being agnostic about the implementation.

The remaining challenge you have to solve now is the implementation of the decorator pattern in Spring Boot. There are plenty of resources which describe how to do so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.