Step 01 — REST skeleton¶
Obiettivo: scheletro Spring Boot avviabile con un endpoint REST minimale.
Cosa costruiamo¶
- L'entry-point
SpringBootFromScratchApplication. - Un controller
ProjectControllerconGETePOST. - DTO
ProjectRequesteProjectResponsecome records immutabili.
Concetti chiave¶
@SpringBootApplication— meta-stereotype che combina@Configuration,@EnableAutoConfiguration,@ComponentScan.@RestController—@Controller+@ResponseBody.ResponseEntity<T>— controllo esplicito su status code e header (Locationsu201 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)
}
}
- Constructor injection — Spring inietta automaticamente, niente
@Autowiredsu field. - 201 Created + Location — standard REST, non
200 OK.
Esercizi¶
- Aggiungi
GET /api/v1/projects/{id}con risposta404se non trovato. - Aggiungi un endpoint
HEADper verificare l'esistenza senza body. - Esponi un endpoint
OPTIONScon 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.