Skip to main content

Spring Boot Basics

Spring Boot is the most widely used Java framework for building web services. It provides sensible defaults, an embedded server and dependency injection.

Create a project​

Generate a project at start.spring.io with Spring Web, Validation and Spring Data JPA, or use the template for your IDE. The entry point:

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

A REST controller​

import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import java.util.*;

record NoteRequest(@NotBlank @Size(max = 500) String text) {}
record Note(long id, String text) {}

@RestController
@RequestMapping("/api/notes")
class NoteController {

private final NoteService service;

NoteController(NoteService service) { // constructor injection
this.service = service;
}

@GetMapping
List<Note> list() {
return service.findAll();
}

@PostMapping
ResponseEntity<Note> create(@Valid @RequestBody NoteRequest req) {
Note created = service.create(req.text());
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}

@GetMapping("/{id}")
Note get(@PathVariable long id) {
return service.find(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
}

Dependency injection​

Spring creates and wires objects (beans) for you.

import org.springframework.stereotype.Service;

@Service
class NoteService {
private final NoteRepository repo;
NoteService(NoteRepository repo) { this.repo = repo; }
// business logic here
}
AnnotationRole
@RestController, @ControllerWeb layer
@ServiceBusiness logic
@RepositoryData access
@Configuration, @BeanExplicit bean definitions
@Value, @ConfigurationPropertiesRead configuration

Configuration​

server:
port: 8080
spring:
datasource:
url: ${DATABASE_URL}
username: ${DB_USER}
password: ${DB_PASSWORD}
jpa:
hibernate:
ddl-auto: validate

Keep secrets in environment variables, never in the repository.

Testing​

@WebMvcTest(NoteController.class)
class NoteControllerTest {
@Autowired MockMvc mvc;
@MockBean NoteService service;

@Test
void rejectsBlankText() throws Exception {
mvc.perform(post("/api/notes")
.contentType("application/json")
.content("{\"text\":\"\"}"))
.andExpect(status().isBadRequest());
}
}

Production readiness​

  • Add spring-boot-starter-actuator for /actuator/health and metrics.
  • Handle errors with @ControllerAdvice.
  • Secure endpoints with Spring Security; hash passwords with bcrypt.
  • See Authentication and web security for concepts.