Search code examples
springspring-restcontroller

extends a class with default mapping


I search a way to have the same base point for different controller

I know i could do

@RestController
@RequestMapping("/extranet")
public class BillingController {

    @GetMapping("/billing")
    public String getBilling() {
        return "Hi From billing!!";
    }
}



@RestController
@RequestMapping("/extranet")
public class PublicationController {

    @GetMapping("/publication")
    public String getPublication() {
        return "Hi From publication!!";
    }
}

Is there a way to do it inheritance?


Solution

  • The First Way - makes the annotation

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @RestController
    @RequestMapping("/extranet")
    public @interface ExtranetRestController {
    
    }
    

    and Add annotation on controller

    @ExtranetRestController
    public class BillingController {
    
      @GetMapping("/billing")
      public String getBilling() {
        return "Hi From billing!!";
      }
    }
    
    @ExtranetRestController
    public class PublicationController {
    
      @GetMapping("/publication")
      public String getPublication() {
        return "Hi From publication!!";
      }
    }
    

    The Second Way - makes the context-path

    Add under line in application.properties

    server.servlet.context-path=/extranet
    

    and Modify controllers

    @RestController
    public class BillingController {
    
      @GetMapping("/billing")
      public String getBilling() {
        return "Hi From billing!!";
      }
    }
    
    @RestController
    public class PublicationController {
    
      @GetMapping("/publication")
      public String getPublication() {
        return "Hi From publication!!";
      }
    }