To implement REST services in Spring 5, follow these steps:
- To enable Spring REST support, add the following starter POM dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency>
- All the annotations of SpringDataConfig needed to implement Spring Data JPA are also needed here for Spring REST configuration.
- Inside org.packt.spring.boot.dao, create a DepartmentRepository that extends JpaRespository, which is the same API class used in the previous recipe:
@RepositoryRestResource(collectionResourceRel="depts", path="depts") public interface DepartmentRepository extends JpaRepository<Department, Integer>{ public List<Department> findByName(@Param("name") String name); public List<Department> findByDeptid( @Param("deptid") Integer deptId); }
The optional annotation @RepositoryRestResource is present because the requirement wants the REST endpoint name to be shorter as /depts than the default, which is /departments. Moreover, the @Param is required to map the local parameter of the operations to the request parameter value sent by the client.
- To parse all the JSON request and response, inject the beans concerning JSON converters to SpringDataConfig from RepositoryRestMvcConfiguration by using @Import. Thus, there is no need to add the com.fasterxml.jackson.core dependency.
- However, even without Spring REST, Spring 5's reactive application can expose any data using @RestController of Spring MVC components. The usual @RequestMapping can still be used to map the handler to the URL with the indicated HTTP method. But the modern way of mapping requests to a URL is through the use of @GetMapping and @PostMapping annotations:
@RestController public class RestServiceController { @Autowired private EmployeeService employeeServiceImpl; @RequestMapping("/objectSampleRest") public String exposeString() { return "Hello World"; } @GetMapping("/monoSampleRest") public Mono<String> exposeMono() { return Mono.just("Hello World"); } @GetMapping("/fluxSampleRest") public Flux<String> exposeFlux() { List<String> names = Arrays.asList("Anna", "John", "Lucy"); return Flux.fromIterable(names) .map((str) -> str.toUpperCase() + "---"); } @GetMapping("/fluxJpaEmps") public Flux<Employee> exposeJpaEmps() { return Flux.fromIterable( employeeServiceImpl.findAllEmps()); } @PostMapping(path = "/fluxAddEmp", consumes = MediaType.APPLICATION_JSON_VALUE) public void addMonoEmp(@RequestBody Mono<Employee> employee){ } @PostMapping(path = "/fluxAddListEmps", consumes = MediaType.APPLICATION_JSON_VALUE) public void addFluxEmp(@RequestBody Flux<Employee> employee){ } }
- Save all files. Then clean and deploy the standalone Spring Boot application. Open a browser and run http://localhost:8093/ch09-flux/fluxJpaEmps.