Quick Reference Spring Boot Cheatsheet
Spring Boot 3 on one page — starters, configuration, REST, validation, constructor
injection, Spring Data JPA, errors, the security filter chain, test slices, and the traps
that show up in interviews.
10 sections 10 tables 15 code snippets The main class @SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
} Run it ./mvnw spring-boot:run
./mvnw test
./mvnw -DskipTests package
java -jar target/shop.jar Starters you will actually add This page is Spring Boot 3 on Java 17. Imports are jakarta.*. A javax.persistence import will not resolve. application.yaml server:
port: 8080
spring:
profiles:
active: dev
app:
page-size: 20 Bind a group of properties @ConfigurationProperties(prefix = "app")
public record AppProperties(int pageSize) {} Prefer one @ConfigurationProperties record over a pile of @Value fields. A missing @Value with no default fails startup. Mappings @RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService books;
public BookController(BookService books) {
this.books = books;
}
@GetMapping
public List<BookResponse> list() {
return books.findAll();
}
@GetMapping("/{id}")
public BookResponse one(@PathVariable long id) {
return books.get(id);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public BookResponse create(@Valid @RequestBody CreateBook body) {
return books.create(body);
}
} A request record public record CreateBook(
@NotBlank String title,
@Positive int pages
) {} What the annotations check @NotBlank text present, not whitespace
@NotNull not null, empty string is allowed
@Email shape of an email
@Positive greater than zero
@Size(max=80) length or collection size So the checks actually run Constructor injection @Service
public class BookService {
private final BookRepository books;
public BookService(BookRepository books) {
this.books = books;
}
} Do not inject fields. final constructor dependencies are required, easy to test, and cannot be half-built. Field @Autowired hides a missing dependency until runtime. Entity and repository @Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
}
public interface BookRepository
extends JpaRepository<Book, Long> {
List<Book> findByTitleContainingIgnoreCase(String title);
} A transaction @Transactional
public BookResponse create(CreateBook body) {
Book saved = books.save(toEntity(body));
return toResponse(saved);
} One place for API errors @RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(BookNotFound.class)
public ProblemDetail missing(BookNotFound ex) {
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
problem.setTitle("Book not found");
problem.setDetail(ex.getMessage());
return problem;
}
} Return a response record, not the JPA entity. The entity carries the persistence model, and a lazy field can throw while Jackson is writing the JSON. Boot 3 chain @Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll())
.httpBasic(Customizer.withDefaults())
.build();
} A controller slice @WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired MockMvc mvc;
@MockitoBean BookService books;
@Test
void listsBooks() throws Exception {
when(books.findAll()).thenReturn(List.of());
mvc.perform(get("/api/books"))
.andExpect(status().isOk());
}
} A @WebMvcTest fails if the controller needs a bean you did not mock. That is the test telling you the constructor has another dependency. Map the entity before it leaves public record BookResponse(long id, String title) {
static BookResponse from(Book book) {
return new BookResponse(book.getId(), book.getTitle());
}
} Scan starts at the app com.shop.ShopApplication scanned
com.shop.web.BookController scanned
com.other.BillingClient not scanned How to use this page: generate a project on start.spring.io with Web, Validation, Data JPA, and Test. Add one entity, one repository, and one controller that returns a record. Then add the Security starter and watch the same route turn into 401 until the filter chain exists. |