Skip to content

hrytsenko/json-data-spring-boot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Quality Gate Status

JSON Data for Spring Boot

This library enables json-data for Spring Boot including serialization, validation and error handling. The following example illustrates integration with Spring Boot, Spring Feign and Spring Sleuth.

@EnableFeignClients
@SpringBootApplication
class Application {

  static class Request extends JsonEntity<Request> {
    String getOwner() {
      return getString("owner");
    }
  }

  static class Response extends JsonEntity<Response> {
  }

  @RestController
  @AllArgsConstructor
  static class GithubController {

    static JsonMapper<Response> TO_RESPONSE = JsonMapper.create(
        JsonResources.readResource("/response-projection.json"), Response::new);

    GithubClient githubClient;

    @PostMapping(
        value = "/list-repositories",
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ValidateRequest("/request-schema.json")
    @ValidateResponse("/response-schema.json")
    @WrapErrors("CANNOT_LIST_REPOSITORIES")
    public Response listRepositories(@RequestBody Request request) {
      var repositories = githubClient.listRepositories(request.getOwner());
      return TO_RESPONSE.map(repositories);
    }

    @FeignClient(name = "github-client", url = "${github.url}")
    interface GithubClient {
      @GetMapping(
          value = "/users/{owner}/repos",
          produces = MediaType.APPLICATION_JSON_VALUE)
      List<JsonBean> listRepositories(@PathVariable("owner") String owner);
    }

  }

  @Bean
  CorrelationSource sleuthSource(Tracer tracer) {
    return () -> tracer.currentSpan().context().traceId();
  }

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

}

Use ValidateRequest to validate inbound JSON entities. Use ValidateResponse to validate outbound JSON entities. Provide ValidatorSource to configure a resource manager for validators.

Use WrapErrors to wrap all unhandled exceptions into ServiceException. Provide CorrelationSource to enable correlations for error responses.