Spring HATEOAS provides Resource and Resources helper classes to wrap a domain object or collection of domain objects instead of extending ResourceSupport (as seen in previous tutorials). The links can be added via instance of these classes.
Example
Domain Object
public class Employee {
private long employeeId;
private String name;
private String dept;
private int salary;
.............
}
Controller
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@GetMapping(value = "/{employeeId}")
public Resource<Employee> getEmployeeById(@PathVariable long employeeId) {
Link selfRelLink = ControllerLinkBuilder.linkTo(
ControllerLinkBuilder.methodOn(EmployeeController.class)
.getEmployeeById(employeeId))
.withSelfRel();
Employee employee = getEmployee(employeeId);
Resource<Employee> resource = new Resource<>(employee);
resource.add(selfRelLink);
return resource;
}
@GetMapping
public Resources<Employee> getEmployees() {
Link selfRelLink = ControllerLinkBuilder.linkTo(
ControllerLinkBuilder.methodOn(EmployeeController.class)
.getEmployees())
.withSelfRel();
List<Employee> employeeList = getEmployeeList();
Resources<Employee> resources = new Resources<>(employeeList);
resources.add(selfRelLink);
return resources;
}
private List<Employee> getEmployeeList() {
//todo: replace with employee service
return List.of(getEmployee(1),
Employee.create(2, "Tom", "IT", 4000));
}
private Employee getEmployee(long employeeId) {
//todo: replace with employee service
return Employee.create(employeeId, "Lara", "Admin", 3000);
}
}
JavaConfig
@EnableWebMvc
@ComponentScan
@Configuration
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class AppConfig {
}
Running
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 will produce following:
{
"employeeId":1,
"name":"Lara",
"dept":"Admin",
"salary":3000,
"_links":{
"self":{
"href":"http://localhost:8080/employees/1"
}
}
}
Accessing http://localhost:8080/employees will produce following:
{
"_embedded":{
"employeeList":[
{
"employeeId":1,
"name":"Lara",
"dept":"Admin",
"salary":3000
},
{
"employeeId":2,
"name":"Tom",
"dept":"IT",
"salary":4000
}
]
},
"_links":{
"self":{
"href":"http://localhost:8080/employees"
}
}
}
Example ProjectDependencies 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
|