1

I'm currently working on a web application where the client (AngularJS) calls RESTful APIs (implemented using spring MVC). My controllers currently look something like this:

@RestController
@RequestMapping("myapp/employees")
public class EmployeesController{
    @Autowired
    private Bus bus;
    @RequestMapping("/", POST)
    public void hireEmployee(@RequestBody HireEmployeeCommand hireEmployeeCommand){
        bus.send(hireEmployeeCommand);
    }
    @RequestMapping("/", DELETE)
    public void fireEmployee(@RequestBody FireEmployeeCommand fireEmployeeCommand){
        bus.send(fireEmployeeCommand);
    }
//etc...
}

Where Commands are DTOs that model a request to a particular transaction (they serve the same purpose of a command in CQRS or a request model in a uncle Bob's Clean Architecture).

The fact that spring is taking care of dispatching the requests to controllers and mapping them to parameters is very convenient. However, I was wondering if there's a way I can make this leaner probably by writing a DSL that will make controller registration look something like this:

routesFor("myapp/employees")
.post("/", HireEmployeeCommand.class)
.delete("/", FireEmployeeCommand.class);

and somewhere else I will have a unified request handler that looks something like:

public void handleRequest(CommandBase cmd){
    //CommandBase is the base class of all commands
    //cmd should be a concrete implementation of CommandBase
    //properties of cmd should have been mapped from the HttpRequest using whatever object mapping utility spring uses
    bus.send(cmd);
}

Is there anyway I can configure spring to "map" the requests to their corresponding commands and dispatch them to the generic request handler?

  • Have a look at http://stackoverflow.com/questions/5758504/is-it-possible-to-dynamically-set-requestmappings-in-spring-mvc – Jan Thomä Nov 09 '15 at 07:18
  • This seems to be useful. This however, covers part of the problem, the other part is how to map the http request to a command given the command type is known. Any way I can use the utility being used by spring to do this? – Shameless Developer Nov 09 '15 at 07:29

0 Answers0