// cheat sheet

Spring Boot Cheat Sheet

A concise reference for the Spring Boot features you reach for every day — core annotations, DI, REST controllers, validation, JPA, Spring Security, testing, and configuration profiles.

Quick Reference

  • @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
  • @RestController returns JSON; @Controller returns views
  • @Service / @Repository / @Component register beans
  • @Autowired (or constructor injection) wires dependencies
  • @Valid + @NotBlank/@Size validate request bodies
  • @SpringBootTest / @WebMvcTest / @DataJpaTest for test slices

Learning Path

Recommended order

  1. 1.Beginner
  2. 2.Intermediate
  3. 3.Advanced

Prerequisites

  • Core Java
  • Maven or Gradle basics
  • HTTP and JSON fundamentals

Skills you will learn

  • Building REST APIs with validation
  • Persisting with Spring Data JPA
  • Securing endpoints with Spring Security
  • Writing slice tests and integration tests

Estimated time

30 minutes to scan, weeks to internalize.

Core annotations

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

@RestController
@RequestMapping("/api/orders")
class OrderController { /* ... */ }

@Service                    // business logic bean
@Repository                 // data-access bean
@Component                  // generic bean
@Configuration              // declares @Bean methods
@ConfigurationProperties    // binds prefixed props to a POJO

Dependency injection

// Preferred: constructor injection — immutable + testable
@Service
class OrderService {
  private final OrderRepository repo;
  OrderService(OrderRepository repo) { this.repo = repo; }
}

// Field injection — avoid in production code
@Autowired private OrderRepository repo;

REST controllers

@RestController
@RequestMapping("/api/orders")
class OrderController {

  @GetMapping("/{id}")
  ResponseEntity<OrderDto> get(@PathVariable Long id) { ... }

  @PostMapping
  @ResponseStatus(HttpStatus.CREATED)
  OrderDto create(@Valid @RequestBody CreateOrderRequest req) { ... }

  @GetMapping
  Page<OrderDto> list(Pageable page,
                      @RequestParam(required = false) String status) { ... }
}

Validation

record CreateOrderRequest(
  @NotBlank @Size(max = 80) String customer,
  @NotEmpty @Size(max = 50) List<@Valid Line> lines
) {}

record Line(@NotNull Long sku, @Positive int qty) {}

// Global exception handler
@RestControllerAdvice
class ApiExceptionHandler {
  @ExceptionHandler(MethodArgumentNotValidException.class)
  ResponseEntity<ApiError> handle(MethodArgumentNotValidException e) { ... }
}

Spring Data JPA

@Entity
class Order {
  @Id @GeneratedValue Long id;
  @Column(nullable = false) String customer;
  @OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true)
  List<Line> lines = new ArrayList<>();
}

interface OrderRepository extends JpaRepository<Order, Long> {
  List<Order> findByCustomerOrderByCreatedAtDesc(String customer);

  @Query("select o from Order o join fetch o.lines where o.id = :id")
  Optional<Order> findWithLines(@Param("id") Long id);
}

Spring Security

@Configuration
@EnableMethodSecurity
class SecurityConfig {
  @Bean
  SecurityFilterChain chain(HttpSecurity http) throws Exception {
    http
      .csrf(csrf -> csrf.disable())
      .authorizeHttpRequests(a -> a
         .requestMatchers("/api/public/**").permitAll()
         .anyRequest().authenticated())
      .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
    return http.build();
  }
}

Testing

@WebMvcTest(OrderController.class)
class OrderControllerTest {
  @Autowired MockMvc mvc;
  @MockBean OrderService service;
}

@DataJpaTest
class OrderRepositoryTest { ... }

@SpringBootTest
@AutoConfigureMockMvc
class OrderIntegrationTest { ... }

// Testcontainers
@Container static PostgreSQLContainer<?> db =
   new PostgreSQLContainer<>("postgres:16");

Configuration & profiles

# application.yml
spring:
  profiles:
    active: ${SPRING_PROFILES_ACTIVE:dev}
  datasource:
    url: jdbc:postgresql://${DB_HOST}/orders
    username: ${DB_USER}
    password: ${DB_PASSWORD}

management:
  endpoints.web.exposure.include: health,info,prometheus
  endpoint.health.probes.enabled: true

Common Mistakes

  • !Field injection instead of constructor injection — kills testability.
  • !Exposing JPA entities directly via REST — couples API to DB schema.
  • !Disabling CSRF without understanding the security trade-off.
  • !Not pinning the Spring Boot BOM version; transitive upgrades break prod.

Production Tips

  • Always return DTOs/records, never entities, from controllers.
  • Use @Transactional only at the service layer; never on controllers.
  • Enable Actuator with /health/liveness + /health/readiness for Kubernetes probes.
  • Set spring.jpa.open-in-view=false to surface N+1s early.

Further Reading

Frequently Asked Questions

How should I use this cheat sheet?

Skim once end-to-end, then keep it open in a pinned tab. Copy a snippet, adapt it to your project, and refer back when memory fails.

Is this cheat sheet up to date?

It's maintained against the latest stable releases in 2026 and revised when commands or APIs change meaningfully.