Commands - sleroy/spring-cqrs-arch GitHub Wiki

Commands

A command is a basic Pojo :

public class CreateUserCommand {
	public String email;
	public String password;
}

Every command is tested using the Validation API and usually the Hibernate validator API.

public class CreateUserCommand {
	@NonEmpty
	@Email
	public String email;
	@NonEmpty
	@Size(minimum=8)
	public String password;
}

It means the gate will validate the command before executing them.

If you pay attention, you should be able to convert your request body or payload directly as a Command.

Send the command

To send a command, you need to send the object through the gate.

To do so, inject the Gate dependency with @Autowired

@RestController
public class MyController {
		@Autowired
		private Gate gate;
}

You have two possibilities to send a command :

  • a synchronous way : gate.dispatch(command);
  • an asynchronous way : gate.dispatchAsync(command);

The methods are returning the results of the command execution.

Write a command service

To write a service that will handle your command, you need to implement a Spring bean defining the interface CommandServiceSpec.

The interface CommandServiceSpec is taking two type parameters :

  • the first one is the command handled : exemple CreateNewCommand
  • the second is the returned type of the command handler: the result produced by the execution of the command.

Example :

@CommandService
public class CreateNewUserCommandService implements ICommandService<CreateNewUserCommand, Integer> {
@Override
	public Integer handle(final CreateNwUserCommand command) throws Exception {

	    return 1;
	}
}

We also recommend to send events to notify the change in the repository. The gate is offering such proxy. The default event bus is in Guava but can be implemented using the Spring applicationEvent or more complex implementations.

@CommandService
public class CreateNewUserCommandService implements CommandServiceSpec<CreateNewUserCommand, Integer> {

@Autowired
private Gate gate;

@Override
	public Integer handle(final CreateNewUserCommand command) throws Exception {
			gate.dispatchEvent(new EventNewUserCreated());
	    return 1;
	}
}