Spring Boot - KeynesYouDigIt/Knowledge GitHub Wiki

Spring Boot

Setup

  • Start new project with Initializr
    • Make sure you add the Spring Web dependency for REST apps

Layout

  • App files are in src/main/java/com/example/project/
  • By default, Maven compiles sources from src/main/java

Controllers

Annotated controllers have flexible method signatures and do not have to extend base classes nor implement specific interfaces.

  • Annotate with @RestController - Tells Spring to render the resulting string back to the caller
    • Equivalent to @Controller + @ResponseBody
  • @ResponseBody means the controller writes directly to the HTTP response instead of going through an HTML template first
  • @RequestMapping("/path") - Routing information for requests, matches all methods. Can be used at the class level for routing.
    • @GetMapping
      • @GetMapping("/{id}") - Dynamic segment, access with @PathVariable Long id in signature
    • @PostMapping
    • @PutMapping
    • @PatchMapping
    • @DeleteMapping
  • Can match on other values: @PostMapping(path = "/pets", consumes = "application/json", produces = "application/json", headers = "myHeader=myValue", params = "myParam=myValue")
  • @ResponseStatus(HttpStatus.CREATED) for setting response
  • Can match paths with exact match, glob, or dynamic segment
  • Multiple patterns are matched by specificity scoring
  • Method arguments include (docs):
    • WebRequest - The entire HTTP response
    • @RequestParam("paramName")
    • @PathVariable
    • @RequestBody
    • @RequestPart (Form)
  • Method return values include (docs):
    • @ResponseBody
    • String - Name of a view to use
    • void - Use if the response status is handled by the @ResponseStatus annotation
  • @JsonView("serializerName") to return a model and serialize the response
  • @CrossOrigin puts CORS headers on responses (allowed at both method and class level)
package com.example.demo;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

  private static final String template = "Hello, %s!";
  private final AtomicLong counter = new AtomicLong();

  @GetMapping("/greeting")
  public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
    return new Greeting(counter.incrementAndGet(), String.format(template, name));
  }
}

Running The Server

With Maven: ./mvnw spring-boot:run (runs on 8080)

Building

  • ./mvnw package builds the app into a .jar file in the /target folder

Questions

  • How does model work?