Spring Boot Hateoas Example
Purpose: In this post, we will learn how we can create a Hibermedia link in API and Testing in spring boot. The steps are given below.
1. Setup and Create Project: Visit here. Spring Boot Rest API Hello World Examples.
Next Step. Spring Boot Parent Dependencies.
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.0.M1</version><relativePath /> <!-- lookup parent from repository --></parent>
Next Step. Add Heteoas Dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Next Step. Spring Boot main class.
Class: Application.java
Note: @SpringBootApplication=@Configuration+ @EnableAutoConfiguration+ @ComponentScan.
package com.bce;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
Next Step. Create Rest Controller.
package com.bce.controller;import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.hateoas.EntityModel;import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;import com.bce.model.Employee;import com.bce.service.EmployeeService;@RestControllerpublic class EmployeeController {@AutowiredEmployeeService employeeService;@GetMapping("/employee")public List<Employee> findAll() {return employeeService.getAllEmployee();}@GetMapping("/employee/{id}")public EntityModel<Employee> findEmployeeById(@PathVariable long id) {EntityModel<Employee> resource = EntityModel.of(employeeService.getEmployeeById(id));WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).findAll());resource.add(linkTo.withRel("all-employees"));return resource;}}
Next Step. Server Port: The default server port is 8080. Wish you want to change open application.properties and add the below line.
server.port=8081
Download Code from GitHub. Download
No comments:
Post a Comment