Originally I just had MyRestController
@CrossOrigin(origins = "*") @RestController public class MyRestController { @RequestMapping(value = "/v1/endpoint", method = {RequestMethod.GET}) public ResponseEntity<Object> endpoint(HttpServletRequest request, HttpServletResponse response) { // etc - duplicate code across controllers with the one // difference of a single function call and its corresponding params } } Then I realized that a lot of the functionality was reused across 6 other controllers so I consolidated them using an abstract BaseController
abstract class BaseController { public ResponseEntity<Object> run(String path, String[] params) { Object result = null; switch (path.toLowerCase()) { // case for each path case MY_PATH: result = someService.myPath(param[0]); break; case MY_OTHER_PATH: result = someService.myOtherPath(param[0], param[1]); break; default: System.out.println("No"); throw new Exception(); } return new ResponseEntity<>(result, HttpStatus.OK); } } and then I changed the class header for MyRestController to
public class MyRestController extends BaseController { and this worked!
My questions are:
- How come I couldn't move the
CrossOriginfromMyRestControllertoBaseController? - I was told to use an
abstractclass. Does this help at all in this use case? - I replaced the duplicate try / catch with a single function using the
pathin aswitchstatement to use the correct method with the correct params. This seems hackish... Is there a better way to do this?
Thanks