Home > Mobile >  Access @PathVariables from parent's @RequestMapping
Access @PathVariables from parent's @RequestMapping

Time:01-27

I'm trying to access the @PathVariables defined in "MyClass"'s @RequestMapping parent. Simplified screnario:

@RestController
@RequestMapping(value = "some/path/{with}/{multiple}/{variables}")
public class ParentClass {...}

This class is sort of a product's base class and should not be edited. Therefore I'm extending 'ParentClass'. In 'MyClass' I want to do something like this:

@GetMapping("/{another}")
public Object get(@PathVariable("another") String another) {...}

I think this is allowed (didn't test yet), but I don't see how I would get all PathVariables that are already defined with 'ParentClass'.

Any idea/ RTFM reference on that is very much appreciated.

CodePudding user response:

Yes, that is possible

@RestController
@RequestMapping("/a/{a}/b/{b}")
class Parent{
}

@RestController
class Child extends Parent{
 
 // take over pathvariables from parent
 @GetMapping("/c/{c}")
 public String abc(@PathVariable String a,@PathVariable String b, @PathVariable String c) {
        return a b c;
 }
 
 // ignore pathvariables from parent
 @GetMapping("/d/{d}")
 public String d(@PathVariable String d){
  return d;
 }

}

Just take over the @Pathvaribles of the Parent-class

Then a request like http://localhost:8080/a/x/b/y/c/z will return "xyz"

And a request like http://localhost:8080/a/ignore-a/b/ignore-b/d/capure-d will return "capure-d"

  •  Tags:  
  • Related