Vai al contenuto

Step 01 — REST skeleton

Obiettivo: scheletro Spring Boot avviabile con un endpoint REST minimale.

Cosa costruiamo

  • L'entry-point SpringBootFromScratchApplication.
  • Un controller ProjectController con GET e POST.
  • DTO ProjectRequest e ProjectResponse come records immutabili.

Concetti chiave

  • @SpringBootApplication — meta-stereotype che combina @Configuration, @EnableAutoConfiguration, @ComponentScan.
  • @RestController@Controller + @ResponseBody.
  • ResponseEntity<T> — controllo esplicito su status code e header (Location su 201 Created).
  • Records — DTO immutabili senza boilerplate (Java 21 stable).

Snippet di riferimento

ProjectController.java
@RestController
@RequestMapping("/api/v1/projects")
public class ProjectController {

    private final ProjectService service;

    public ProjectController(ProjectService service) {
        this.service = service;          // (1)
    }

    @PostMapping
    public ResponseEntity<ProjectResponse> create(
            @Valid @RequestBody ProjectRequest request,
            UriComponentsBuilder uriBuilder
    ) {
        ProjectResponse created = service.create(request);
        URI location = uriBuilder.path("/api/v1/projects/{id}")
                                 .buildAndExpand(created.id())
                                 .toUri();
        return ResponseEntity.created(location).body(created);  // (2)
    }
}
  1. Constructor injection — Spring inietta automaticamente, niente @Autowired su field.
  2. 201 Created + Location — standard REST, non 200 OK.

Esercizi

  1. Aggiungi GET /api/v1/projects/{id} con risposta 404 se non trovato.
  2. Aggiungi un endpoint HEAD per verificare l'esistenza senza body.
  3. Esponi un endpoint OPTIONS con CORS configurato.

Pitfall

Field injection con @Autowired

Evita. Constructor injection rende il bean testabile senza Spring e i field final.

200 OK su creazione

REST 101: la creazione torna 201 + Location.

Riferimenti nel codice