Power Of Java 8 Default Method In Spring Controller


Imagine your application has multiple controllers (for Quite a long period of time) for each domain object (EntityOneController, EntityTwoController etc) having its own hierarchy and now a common endpoint has to be added in each controller incrementally, having every thing same however differing in very little aspect.


Lets say that the common endpoint would expose swagger detail for that each entity. One option would be to write the same logic one by one in each controller, however that would duplicate lots of code in every controller.


Java 8  Default Method To The Rescue

Here is the Java 8 Default Interface with Spring @Controller Annotation, as can be seen here it has common implementation, but implementors can provide their custom behavior as well.



public interface SwaggerController { 
  String getName(String foo); 
  @RequestMapping(value = "/swagger/{foo}", method = RequestMethod.GET) 
  default String hyperschema(Model model, @PathVariable String foo) { 
    model.addAttribute("name", getName(foo)); 
    return "welcome"; 

Here is one of the Implementations

public class EntityOneController extends EntityOneBaseController implements SwaggerController { 
  @Override public String getName(String name) { 
    return "Entity1 " + name; 

Endpoint URL would be /entity1/swagger

Here is another implementations

public class EntityTwoController extends EntityTwoBaseController  implements SwaggerController {
 @Override public String getName(String foo) { 
    return "Entitiy2 " + foo; 

Endpoint URL would be /entity2/swagger

We have achieved the same functionality, without duplicating code!