Simple mediator implementation in Java.
Greatly inspired by jbogard's .NET implementation.
Add MediatR to your build.gradle
implementation 'io.github.lucasbuccilli:mediatR:1.0.2'
Create a MediatR bean
@Configuration
public class MediatRConfig {
@Bean
public MediatR mediatR(ApplicationContext applicationContext) {
return MediatRFactory.getMediatR(applicationContext);
}
}
MediatR has two kind of messages it dispatches:
Request/response messages, dispatched to a single handler
Request<T>
RequestHandler<T extends Request>
Event messages, dispatched to multiple handlers
Event
EventHandler<T extends Event>
Create a request
public class GetUserRequest implements Request<User> {
private int userId;
...
}
Create a handler
Note: A handler must be annotated with @Component
or @Service
@Component
public class GetUserRequestHandler implements RequestHandler<GetUserRequest> {
@Override
public User handle(GetUserRequest request) {
...
return user;
}
}
Send the request with MediatR and tada
var user = mediatR.send(new GetUserRequest(1));
Events are similar to requests, but you can register multiple handlers for the same event.
public class DeleteUserEvent implements Event {
private int userId;
...
}
@Component
public class DeleteUserEventHandlerOne implements EventHandler<DeleteUserEvent> {
@Override
public void handle(DeleteUserEvent event) {
...
}
}
@Component
public class DeleteUserEventHandlerTwo implements EventHandler<DeleteUserEvent> {
@Override
public void handle(DeleteUserEvent event) {
...
}
}
mediatR.send(new DeleteUserEvent(1));
MediatR also supports asynchronous operations
CompletableFuture<User> userFurure = mediatR.sendAsync(new GetUserRequest(1));
CompletableFuture<Void> userFurure = mediatR.sendAsync(new DeleteUserEvent(1));