ENGIMY.IO - CHEATSHEET
SPRING BOOT × QUICK REFERENCE
REFERENCE vSpring Boot 3.x

Spring Boot Quick Reference

Everything you need day‑to‑day – annotations, configuration, and development.

What is Spring Boot?

  • Framework for building production‑ready Spring applications
  • Auto‑configuration – reduces boilerplate
  • Embedded servers (Tomcat, Jetty, Undertow)
  • Starter dependencies – pre‑configured modules
  • Actuator – monitoring and health checks
  • Production‑ready features

Project Setup

Spring Initializr

  • Web: https://start.spring.io
  • CLI: spring init --dependencies=web,data-jpa,postgresql my-app
  • IDE: IntelliJ, Eclipse, VS Code

Maven Dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.0</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Main Application Class

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

@SpringBootApplication =

  • @Configuration – bean definitions
  • @EnableAutoConfiguration – auto‑configuration
  • @ComponentScan – scan for components

Core Annotations

Configuration
  • @Configuration – class with bean definitions
  • @Bean – defines a bean
  • @Component – generic component
  • @Service – service layer
  • @Repository – data access layer
  • @Controller – MVC controller
  • @RestController – REST API controller
  • @Autowired – dependency injection
  • @Qualifier – disambiguate beans
  • @Primary – preferred bean
  • @Value – inject property
  • @ConfigurationProperties – bind properties
Spring MVC
  • @RequestMapping – map requests
  • @GetMapping – GET requests
  • @PostMapping – POST requests
  • @PutMapping – PUT requests
  • @DeleteMapping – DELETE requests
  • @PatchMapping – PATCH requests
  • @PathVariable – URL variable
  • @RequestParam – query parameter
  • @RequestBody – request body
  • @ResponseBody – response body
  • @ResponseStatus – HTTP status
  • @ExceptionHandler – handle exceptions
  • @ControllerAdvice – global exception handling
  • @RestControllerAdvice – global REST exception handling

REST API Example

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        return userService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public User createUser(@RequestBody User user) {
        return userService.save(user);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        return userService.update(id, user);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@PathVariable Long id) {
        userService.delete(id);
    }
}

Data Access (Spring Data JPA)

Entity

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(unique = true, nullable = false)
    private String email;

    @Column(name = "created_at")
    @CreationTimestamp
    private LocalDateTime createdAt;

    @Column(name = "updated_at")
    @UpdateTimestamp
    private LocalDateTime updatedAt;

    // getters, setters, constructors
}

Repository

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);

    List<User> findByNameContainingIgnoreCase(String name);

    @Query("SELECT u FROM User u WHERE u.email LIKE %:domain%")
    List<User> findByEmailDomain(@Param("domain") String domain);
}

Service

@Service
@Transactional
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> findAll() {
        return userRepository.findAll();
    }

    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }

    public User save(User user) {
        return userRepository.save(user);
    }

    public User update(Long id, User user) {
        User existing = userRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("User not found"));
        existing.setName(user.getName());
        existing.setEmail(user.getEmail());
        return userRepository.save(existing);
    }

    public void delete(Long id) {
        userRepository.deleteById(id);
    }
}

Configuration

application.properties

# Server
server.port=8080
server.servlet.context-path=/api

# Database
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=secret

# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

# Logging
logging.level.org.springframework.web=DEBUG
logging.level.com.example=TRACE

application.yml

server:
  port: 8080
  servlet:
    context-path: /api

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: postgres
    password: secret
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true

logging:
  level:
    org.springframework.web: DEBUG
    com.example: TRACE

Profile‑Specific Properties

  • application-dev.properties – dev profile
  • application-prod.properties – prod profile
  • Activate: spring.profiles.active=dev

Dependency Injection

// Field injection (discouraged)
@Autowired
private UserService userService;

// Constructor injection (recommended)
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }
}

// Setter injection
@Autowired
public void setUserService(UserService userService) {
    this.userService = userService;
}

Validation

@Entity
public class User {
    @NotNull
    @Size(min = 2, max = 100)
    private String name;

    @NotNull
    @Email
    @Column(unique = true)
    private String email;

    @Min(18)
    @Max(120)
    private Integer age;
}

@RestController
public class UserController {
    @PostMapping
    public User create(@Valid @RequestBody User user) {
        return userService.save(user);
    }
}

Common Validation Annotations

  • @NotNull
  • @NotEmpty – not null and not empty
  • @NotBlank – not null and trimmed length > 0
  • @Size – min/max size
  • @Min / @Max – numeric range
  • @Email
  • @Pattern – regex
  • @Past / @Future – date
  • @AssertTrue / @AssertFalse

Exception Handling

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleValidation(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error ->
            errors.put(error.getField(), error.getDefaultMessage())
        );
        return errors;
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleNotFound(ResourceNotFoundException ex) {
        return new ErrorResponse(ex.getMessage(), HttpStatus.NOT_FOUND.value());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse handleGeneric(Exception ex) {
        return new ErrorResponse("Internal server error", 500);
    }
}

Spring Boot Actuator

# application.properties
management.endpoints.web.exposure.include=health,info,metrics
management.info.build.enabled=true
management.info.env.enabled=true

# Endpoints
/actuator/health
/actuator/info
/actuator/metrics
/actuator/beans
/actuator/env

Testing

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    public void testGetUsers() throws Exception {
        mockMvc.perform(get("/api/users"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }

    @Test
    public void testCreateUser() throws Exception {
        String userJson = "{\"name\":\"Alice\",\"email\":\"alice@ex.com\"}";
        mockMvc.perform(post("/api/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(userJson))
            .andExpect(status().isCreated());
    }
}

Spring Boot Starters

  • spring‑boot‑starter‑web – REST API
  • spring‑boot‑starter‑data‑jpa – JPA/Hibernate
  • spring‑boot‑starter‑security – Security
  • spring‑boot‑starter‑test – Testing
  • spring‑boot‑starter‑validation – Validation
  • spring‑boot‑starter‑actuator – Monitoring
  • spring‑boot‑starter‑oauth2‑client – OAuth2
  • spring‑boot‑starter‑mail – Email
  • spring‑boot‑starter‑redis – Redis
  • spring‑boot‑starter‑amqp – RabbitMQ
  • spring‑boot‑starter‑kafka – Kafka
  • spring‑boot‑starter‑thymeleaf – Templates

Common Spring Boot Properties

Property Description
server.port Port to listen on
server.servlet.context-path Context path
spring.datasource.url Database URL
spring.datasource.username Database username
spring.datasource.password Database password
spring.jpa.hibernate.ddl-auto Schema generation (none, validate, update, create, create‑drop)
spring.jpa.show-sql Log SQL
logging.level.* Log levels
spring.profiles.active Active profiles

Best Practices

  • Use constructor injection – over field injection.
  • Use @RestController for REST APIs.
  • Use DTOs – separate API layer from entity layer.
  • Use @Valid – for request validation.
  • Use global exception handling@ControllerAdvice.
  • Use profiles – for different environments.
  • Use Actuator – for monitoring and health checks.
  • Write tests – unit and integration tests.
  • Use @Transactional – for data consistency.
  • Use Spring Security – for authentication and authorisation.
  • Externalise configuration – use properties files or environment variables.
  • Use Lombok – reduce boilerplate code.
  • Use MapStruct – for entity‑DTO mapping.
  • Avoid @Autowired on fields – use constructor injection.
  • Keep controllers thin – business logic in services.
  • Use pagination – for large datasets.
  • Log meaningful messages – at appropriate levels.
📌 Quick Reference
Starters: spring‑boot‑starter‑web, data‑jpa, security, test, actuator
Annotations: @SpringBootApplication, @RestController, @Service, @Repository, @Autowired
REST: @GetMapping, @PostMapping, @PathVariable, @RequestParam, @RequestBody
JPA: @Entity, @Id, @GeneratedValue, JpaRepository, @Query
Validation: @NotNull, @Size, @Email, @Valid
Error handling: @ControllerAdvice, @ExceptionHandler
Actuator: /actuator/health, /actuator/metrics
Profiles: application-{profile}.properties, spring.profiles.active
← Back to All Cheatsheets