Skip to main content
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

A Boot 3 app

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

StarterBrings in
spring-boot-starter-webSpring MVC, Jackson, embedded Tomcat. Port 8080
spring-boot-starter-validationBean Validation. Without it, @Valid does not check
spring-boot-starter-data-jpaHibernate and Spring Data repositories
spring-boot-starter-securityEvery route is locked until you write a filter chain
spring-boot-starter-testJUnit 5, Mockito, MockMvc, AssertJ

This page is Spring Boot 3 on Java 17. Imports are jakarta.*. A javax.persistence import will not resolve.

Configuration

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) {}

Which file wins

SourceRule
application.yamlAlways loaded
application-dev.yamlLoaded when the dev profile is active, and overrides the base file
Environment variableBeats the file. SERVER_PORT maps to server.port
@ConfigurationPropertiesBinds a prefix. page-size maps to pageSize
@ConfigurationPropertiesScanPut it on the application class so the record becomes a bean

Prefer one @ConfigurationProperties record over a pile of @Value fields. A missing @Value with no default fails startup.

REST controllers

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);
  }
}

Mapping pieces

AnnotationMeaning
@RestController@Controller plus @ResponseBody. The return value is the JSON body
@GetMapping / @PostMappingHTTP method. @RequestMapping sets the shared path
@PathVariableA segment of the path. The name must match {id}
@RequestParamA query string, as in /api/books?q=java
@RequestBodyJSON deserialized into the argument
ResponseEntityWhen you must set status and headers yourself. Otherwise use @ResponseStatus

Validation

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

NeedWhy
spring-boot-starter-validationThe implementation of Bean Validation
@Valid on the argumentWithout it, the annotations are ignored
jakarta.validation importsBoot 3. The javax.validation names are Boot 2
A failed checkSpring responds with 400 before your method runs

Injection

Constructor injection

@Service
public class BookService {
  private final BookRepository books;

  public BookService(BookRepository books) {
    this.books = books;
  }
}

Stereotypes

AnnotationRole
@ComponentA bean. The others are special cases of this
@ServiceBusiness logic. Same mechanism as @Component
@RepositoryData access. Also translates persistence exceptions
@RestControllerAn HTTP adapter. Keep it thin
One constructorSpring calls it. You do not need @Autowired
Component scanOnly the application package and its subpackages. A sibling package is invisible

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.

Spring Data JPA

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);
}

Persistence rules

RuleDetail
JpaRepositoryCRUD plus paging. You do not write the SQL for save and findById
Derived queryThe method name is the query. A typo still compiles and fails at startup
ddl-auto: updateHandy on a laptop. Dangerous on a production database. Prefer Flyway and validate
@TransactionalRolls back on a runtime exception. A checked exception commits unless you set rollbackFor
Call through the beanthis.create() inside the same class skips the transaction proxy
No-arg constructorJPA needs one on the entity. A record is a poor entity

Error responses

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;
  }
}

How status is chosen

ToolUse
ProblemDetailAn RFC 9457 body. Boot 3 already knows this type
ResponseStatusExceptionThrow it from a service when you do not want a custom type
@ResponseStatus on an exceptionA fixed status for that type
@RestControllerAdviceHandles exceptions from every controller, not one class
Validation failureAlready a 400. Handle MethodArgumentNotValidException only to reshape the body

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.

Security filter chain

Boot 3 chain

@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
  return http
      .authorizeHttpRequests(auth -> auth
          .requestMatchers("/api/**").authenticated()
          .anyRequest().permitAll())
      .httpBasic(Customizer.withDefaults())
      .build();
}

What the starter changes

FactConsequence
Adding the starterEvery endpoint requires login, including ones that used to be public
Generated passwordPrinted at startup for the user user, unless you set one
SecurityFilterChain beanThe Boot 3 way. WebSecurityConfigurerAdapter was removed
CSRFLeave it on for browser forms. A bearer-token API usually disables it
requestMatchersFirst match wins. Put specific paths before anyRequest

Test slices

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());
  }
}

Which annotation

AnnotationStarts
@WebMvcTestThe web layer only. You mock the service
@DataJpaTestJPA and an in-memory database. Rolls the test transaction back
@SpringBootTestThe whole application. Use it for a few end-to-end cases, not every method
@MockitoBeanReplaces a bean with a mock. Boot 3.4 and later. Older tests say @MockBean
MockMvcCalls the controller without a real socket

A @WebMvcTest fails if the controller needs a bean you did not mock. That is the test telling you the constructor has another dependency.

Interview traps

Traps worth memorising

TrapWhat happensPrefer
javax.* on Boot 3The import does not existjakarta.persistence, jakarta.validation
Bean in a sibling packageNever created. Endpoints 404 or injection failsA subpackage of the application class
@Valid without the validation starterBad JSON is acceptedAdd spring-boot-starter-validation
Field @AutowiredThe object can be used before it is setConstructor injection and final
ddl-auto: update in prodHibernate alters the live schemaFlyway or Liquibase, and validate
this.save() inside the serviceNo transaction. The annotation is on the proxyCall the method through the injected bean
Checked exception in @TransactionalThe transaction commitsrollbackFor = Exception.class when you mean it
Security starter with no chainThe whole API returns 401A SecurityFilterChain bean
Returning a Book entityLazy fields and extra columns leak into JSONA BookResponse record
open-in-view left onThe session stays open during the view. Boot logs a warningFetch what you need in the service, then turn it off
@SpringBootTest for one routeBoots the database and every bean@WebMvcTest
Derived query typoCompiles. Fails when the repository is createdRead the startup error. The method name is the query

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.