SomeGuyOnAComputer
SomeGuyOnAComputer

Reputation: 6208

Define a base rest controller in spring boot?

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:

Thanks

Upvotes: 0

Views: 5818

Answers (1)

ndrone
ndrone

Reputation: 3582

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.

Upvotes: 1

Related Questions