Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to have an annotated Abstract Controller class - Spring MVC

Does it make sense to have an annotated (@Controller) Abstract class in Spring MVC driven container, basically would like to place most of the reusable methods such as exception handlers in the Abstract class and extend that with the base class, so that don't have to repeat the same boilerplate code. For example.

Abstract Controller Class:

    @Controller
    abstract class AbstractExternalController {

    @ExceptionHandler(NoSuchRequestHandlingMethodException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public @ResponseBody ResponseModel handleNotFoundException() {
            final ResponseModel response = new ErrorModel();
            response.setStatus("404");
                response.setMessage("Resource Not Found");
                return response;
             } 
...

    }

Base Controller Class

@Controller
class ExternalControllerXXX extends AbstractExternalController  {

...
}
like image 566
MasterV Avatar asked Nov 09 '12 17:11

MasterV


1 Answers

It is unnecessary to annotate your AbstractExternalController class with the @Controller anntation, although, leaving it there will not break anything. Regardless of whether or not you have the @Controller annotation, you certainly can have the method annotations, and they will work. Your ExternalControllerXXX extending it will be added to the application context (because it is annotated with a streotype annotation), and the @ExceptionHandler and @ResponseStatus annotations will be honored.

like image 76
nicholas.hauschild Avatar answered Oct 16 '22 10:10

nicholas.hauschild