2

In my Java Spring MVC 4 project, I have an AbstractRESTController with an update method:

@RequestMapping(
        value="/{id}",
        method=RequestMethod.PUT,
        consumes={MediaType.APPLICATION_JSON_VALUE}
)
public @ResponseBody ResponseEntity<T> update(@PathVariable ID id, 
    @RequestParam String token, @RequestBody T json) {
        [do fancy stuff]
}

and an extending class, let's call it MyController. Usually I want to use the method from the abstract class, but in MyController I have a special case (yay!), so I need to do further work.

My idea was to just override the @RequestMapping in the child class, do my additional fancy stuff and afterwards call the super class' update method from the MyController.update method. But this does not work, because I get an ambiguous mapping error during compilation.

Is there a way to make Spring override the parent class request mapping? I would like to avoid splitting the routes.

1
  • As a route is intended to point at a specific method, I don't think you're going to be able to do it quite that way. Perhaps if you were to do your processing of the request in a separate method and override that method in those child classes which need their own implementation? Commented Jan 12, 2015 at 16:08

1 Answer 1

3

As you have noticed you can't do this because the ambiguous mapping.

If you want execute some additional code, you can use something like hook methods. So, define in your AbstractRESTController an empty method like this:

protected void doFancyStuff() {

}

Obs.: the empty method is a better choice here, and not an abstract one, to avoid the need to implement even with empty method body in all concrete controller.

Change the update method to call the hook method:

@RequestMapping(
        value="/{id}",
        method=RequestMethod.PUT,
        consumes={MediaType.APPLICATION_JSON_VALUE}
)
public @ResponseBody ResponseEntity<T> update(@PathVariable ID id, 
    @RequestParam String token, @RequestBody T json) {
        doFancyStuff();
}

And in MyController you will override and implement doFancyStuff method.

Sign up to request clarification or add additional context in comments.

3 Comments

I really like this idea, and it works for me. I do not think that this is 100% elegant but maybe still the best solution in this case.
@dexBerlin I agree with you, this is not 100% elegant. I like to use methods such as doBeforeUpdate, doAfterUpdate, etc. To abstract common and specific behaviors.
i have a AbstractCtrl that calls my services rest layer. this solution fits perfect.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.