Close

Spring HATEOAS - Using @EnableHypermediaSupport to enable HAL format

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

Spring HATEOAS allows to activate a particular hypermedia representation format by using @EnableHypermediaSupport annotation. This annotation takes a HypermediaType enum as argument. Currently only HAL is supported.

Example

JavaConfig

@EnableWebMvc
@ComponentScan
@Configuration
@EnableHypermediaSupport(type = { EnableHypermediaSupport.HypermediaType.HAL })
public class AppConfig {
}

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) {
      Employee employeeById = ControllerLinkBuilder.methodOn(EmployeeController.class)
                                                   .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 produces:

{
   "employeeId": 1,
   "name": "Lara",
   "dept": "Admin",
   "salary": 3000,
   "_links": {
         "self": {
         "href": "http://localhost:8080/employees/1"
         }
      }
}

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
  • spring-plugin-core 1.2.0.RELEASE: Core plugin infrastructure.
  • 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

Using HAL format Select All Download
  • spring-hateoas-enable-hypermedia-support-with-hal
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • AppConfig.java

    See Also