0

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 CrossOrigin from MyRestController to BaseController ?
  • I was told to use an abstract class. Does this help at all in this use case?
  • I replaced the duplicate try / catch with a single function using the path in a switch statement to use the correct method with the correct params. This seems hackish... Is there a better way to do this?

Thanks

1 Answer 1

1

Looking at the documentation for the annotation CrossOrigin https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html

This is why it didn't work is because your BaseController doesn't have any methods to add to the RequestMappingHandlerMapping so that is why it didn't work.

As far as the BaseController being abstract it is not necessary unless you have a method that you want your extending controllers to overwrite.

Update about Switch

That is really up to you depending on how many controller methods are going to fall into each case. If multiple methods fall into the MY_PATH case then I believe you are ok, but I can see where the cases could turn into a very lengthy switch statement. It's really up to you as the maintainer. In my opinion, I would break the switch statement cases into different methods and let the controller that extend call that method. But that is personal preference.

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

2 Comments

Ok wonderful, I understand both of your answers. Thank you! Do you mind also taking a crack at the last question?
I suppose I'll keep everything the same and just change the abstract to a normal class. Thanks again!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.