Close

Spring HATEOAS - Building Links Pointing To Methods

[Updated: Jul 6, 2018, Created: Jul 5, 2018]

In Spring HATEOAS we can easily build links pointing to controller methods by using ControllerLinkBuilder#methodOn(). This method returns a proxy of the controller which records the last invocation of the method to build the links.

Example

Resource Object

public class Employee extends ResourceSupport {
  private long employeeId;
  private String name;
  private String dept;
  private int salary;
    .............
}

Controller

@RestController
@RequestMapping("/employees")
public class EmployeeController {

  @GetMapping(value = "/{employeeId}")
  public Employee getEmployeeById(@PathVariable long employeeId) {
      EmployeeController theController = ControllerLinkBuilder.methodOn(EmployeeController.class);
      Employee employeeById = theController.getEmployeeById(employeeId);
      Link selfLink = ControllerLinkBuilder.linkTo(employeeById).withSelfRel();

      Employee employee = getEmployee(employeeId);
      employee.add(selfLink);
      return employee;
  }

  private Employee getEmployee(long employeeId) {
      //todo: replace with employee service
      return Employee.create(employeeId, "Lara", "Admin", 3000);
  }
}

Running example

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Accessing http://localhost:8080/employees/1 in a web browser will render:

{
"employeeId": 1,
"name": "Lara",
"dept": "Admin",
"salary": 3000,
"links": [
{
   "rel": "self",
   "href": "http://localhost:8080/employees/1",
   "hreflang": null,
   "media": null,
   "title": null,
   "type": null,
   "deprecation": null
}
]}

Example Project

Dependencies and Technologies Used:

  • spring-hateoas 0.24.0.RELEASE: Library to support implementing representations for hyper-text driven REST web services.
    Uses org.springframework:spring-web-mvc version 4.3.12.RELEASE
  • jackson-databind 2.9.5: General data-binding functionality for Jackson: works on core streaming API.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 10
  • Maven 3.5.4

Building Links Pointing To Methods Select All Download
  • spring-hateoas-method-pointer-link-builder
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EmployeeController.java

    See Also