Cheat Sheet

Spring Boot Cheat Sheet


1. Create a New Spring Boot Project


spring init --type=web --project-name=myproject

2. Add Dependencies to pom.xml


<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
</dependencies>

3. Create a New Spring Boot Application


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

4. Create a New REST Controller


@RestController
@RequestMapping(`/api`)
public class MyController {
  @GetMapping(`/hello`)
  public String hello() {
    return `Hello, World!`;
  }
}

5. Use @Autowired for Dependency Injection


@Service
public class MyService {
  @Autowired
  private MyRepository myRepository;
  
  public List<MyEntity> getAll() {
    return myRepository.findAll();
  }
}

6. Use @Value for Property Injection


@Service
public class MyService {
  @Value(`${my.property}`)
  private String myProperty;
  
  public String getMyProperty() {
    return myProperty;
  }
}

7. Use @Configuration for Configuration Classes


@Configuration
public class MyConfig {
  @Bean
  public MyBean myBean() {
    return new MyBean();
  }
}

8. Use @Bean for Bean Definitions


@Configuration
public class MyConfig {
  @Bean
  public MyBean myBean() {
    return new MyBean();
  }
}

9. Use @ComponentScan for Component Scanning


@SpringBootApplication
@ComponentScan(basePackages = `com.example`)
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}

10. Use @EnableAutoConfiguration for Auto-Configuration


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

11. Use @SpringBootApplication for Spring Boot Applications


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

12. Use @RestController for REST Controllers


@RestController
@RequestMapping(`/api`)
public class MyController {
  @GetMapping(`/hello`)
  public String hello() {
    return `Hello, World!`;
  }
}

13. Use @GetMapping for GET Requests


@RestController
@RequestMapping(`/api`)
public class MyController {
  @GetMapping(`/hello`)
  public String hello() {
    return `Hello, World!`;
  }
}

14. Use @PostMapping for POST Requests


@RestController
@RequestMapping(`/api`)
public class MyController {
  @PostMapping(`/hello`)
  public String hello(@RequestBody MyRequest request) {
    return `Hello, ` + request.getName();
  }
}

15. Use @PutMapping for PUT Requests


@RestController
@RequestMapping(`/api`)
public class MyController {
  @PutMapping(`/hello`)
  public String hello(@RequestBody MyRequest request) {
    return `Hello, ` + request.getName();
  }
}

16. Use @DeleteMapping for DELETE Requests


@RestController
@RequestMapping(`/api`)
public class MyController {
  @DeleteMapping(`/hello`)
  public String hello() {
    return `Hello, World!`;
  }
}

17. Use @PathVariable for Path Variables


@RestController
@RequestMapping(`/api`)
public class MyController {
  @GetMapping(`/hello/{name}`)
  public String hello(@PathVariable String name) {
    return `Hello, ` + name;
  }
}

18. Use @RequestParam for Request Parameters


@RestController
@RequestMapping(`/api`)
public class MyController {
  @GetMapping(`/hello`)
 public String hello(@RequestParam String name) {
    return `Hello, ` + name;
  }
}

19. Use @RequestBody for Request Body


@RestController
@RequestMapping(`/api`)
public class MyController {
  @PostMapping(`/hello`)
  public String hello(@RequestBody MyRequest request) {
    return `Hello, ` + request.getName();
  }
}

20. Use @ResponseBody for Response Body


@RestController
@RequestMapping(`/api`)
public class MyController {
  @GetMapping(`/hello`)
  @ResponseBody
  public String hello() {
    return `Hello, World!`;
  }
}

21. Use @ExceptionHandler for Exception Handling


@RestController
@RequestMapping(`/api`)
public class MyController {
  @GetMapping(`/hello`)
  public String hello() {
    throw new RuntimeException(`Error occurred`);
  }
  @ExceptionHandler(RuntimeException.class)
  public ResponseEntity<String> handleException(RuntimeException e) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
  }
}

22. Use @ControllerAdvice for Global Exception Handling


@ControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(RuntimeException.class)
  public ResponseEntity<String> handleException(RuntimeException e) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
  }
}

23. Use @ResponseStatus for Custom Response Status


@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
  public ResourceNotFoundException(String message) {
    super(message);
  }
}

24. Use @Transactional for Transaction Management


@Service
public class MyService {
  @Transactional
  public void performTransaction() {
    // Transactional code here
  }
}

25. Use Spring Data JPA for Database Access


@Repository
public interface MyRepository extends JpaRepository<MyEntity, Long> {
}

26. Use @Entity for JPA Entities


@Entity
public class MyEntity {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  
  private String name;
}

27. Use @Table for Custom Table Names


@Entity
@Table(name = `my_table`)
public class MyEntity {
  // Fields and methods
}

28. Use @Column for Custom Column Names


@Entity
public class MyEntity {
  @Column(name = `my_name`)
  private String name;
}

29. Use @OneToMany for One-to-Many Relationships


@Entity
public class Parent {
  @OneToMany(mappedBy = `parent`)
  private List<Child> children;
}

30. Use @ManyToOne for Many-to-One Relationships


@Entity
public class Child {
  @ManyToOne
  @JoinColumn(name = `parent_id`)
  private Parent parent;
}

31. Use @ManyToMany for Many-to-Many Relationships


@Entity
public class Student {
  @ManyToMany
  @JoinTable(name = `student_course`,
    joinColumns = @JoinColumn(name = `student_id`),
    inverseJoinColumns = @JoinColumn(name = `course_id`))
  private List<Course> courses;
}

32. Use @JoinColumn for Custom Join Columns


@Entity
public class Child {
  @ManyToOne
  @JoinColumn(name = `parent_id`, referencedColumnName = `id`)
  private Parent parent;
}

33. Use @Query for Custom Queries


@Repository
public interface MyRepository extends JpaRepository<MyEntity, Long> {
  @Query(`SELECT e FROM MyEntity e WHERE e.name = ?1`)
  List<MyEntity> findByName(String name);
}

34. Use @Modifying for Update/Delete Queries


@Repository
public interface MyRepository extends JpaRepository<MyEntity, Long> {
  @Modifying
  @Query(`DELETE FROM MyEntity e WHERE e .name = ?1`)
  void deleteByName(String name);
}

35. Use @Transactional for Rollback on Exception


@Service
public class MyService {
  @Transactional(rollbackFor = Exception.class)
  public void performTransaction() {
    // Transactional code here
  }
}

36. Use Spring Security for Authentication


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and()
      .formLogin();
  }
}

37. Use @PreAuthorize for Method Security


@Service
public class MyService {
  @PreAuthorize(`hasRole('ADMIN')`)
  public void adminMethod() {
    // Admin-only method
  }
}

38. Use @Secured for Role-Based Security


@Service
public class MyService {
  @Secured(`ROLE_USER`)
  public void userMethod() {
    // User-only method
  }
}

39. Use @EnableGlobalMethodSecurity for Method Security


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends WebSecurityConfigurerAdapter {
}

40. Use Spring Boot Actuator for Monitoring


// Add dependency in pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

41. Use /actuator for Health Checks


GET /actuator/health

42. Use /actuator/info for Application Info


GET /actuator/info

43. Use Spring Boot Profiles for Environment Management


// application.properties
spring.profiles.active=dev

44. Use @Profile for Profile-Specific Beans


@Configuration
@Profile(`dev`)
public class DevConfig {
  @Bean
  public MyBean myBean() {
    return new MyBean(`Development`);
  }
}

45. Use Spring Boot DevTools for Development


// Add dependency in pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
  <scope>runtime</scope>
</dependency>

46. Use @Scheduled for Scheduled Tasks


@EnableScheduling
@Service
public class MyService {
  @Scheduled(fixedRate = 5000)
  public void scheduledTask() {
    // Task to run every 5 seconds
  }
}

47. Use @Async for Asynchronous Methods


@EnableAsync
@Service
public class MyService {
  @Async
  public CompletableFuture<String> asyncMethod() {
    // Asynchronous code here
    return CompletableFuture.completedFuture(`Done`);
  }
}

48. Use Spring Boot Testing for Unit Tests


@SpringBootTest
public class MyServiceTests {
  @Autowired
  private MyService myService;
  @Test
  public void testService() {
    assertNotNull(myService);
  }
}

49. Use @MockBean for Mocking Beans in Tests


@SpringBootTest
public class MyServiceTests {
  @MockBean
  private MyRepository myRepository;
  @Test
  public void testService() {
    when(myRepository.findAll()).thenReturn(new ArrayList<>());
    // Test logic here
  }
}

50. Use @DataJpaTest for JPA Tests


@DataJpaTest
public class MyRepositoryTests {
  @Autowired
  private MyRepository myRepository;
  @Test
  public void testFindByName() {
    // Test logic here
  }
}

51. Use @WebMvcTest for MVC Tests


@WebMvcTest(MyController.class)
public class MyControllerTests {
  @Autowired private MockMvc mockMvc;
  @Test
  public void testHello() throws Exception {
    mockMvc.perform(get(`/api/hello`))
      .andExpect(status().isOk())
      .andExpect(content().string(`Hello, World!`));
  }
}

52. Use @SpringBootTest for Integration Tests


@SpringBootTest
public class MyApplicationTests {
  @Test
  public void contextLoads() {
    // Test logic here
  }
}

53. Use @TestPropertySource for Test Properties


@SpringBootTest
@TestPropertySource(locations = `classpath:test.properties`)
public class MyServiceTests {
  // Test logic here
}

54. Use @ActiveProfiles for Active Profiles in Tests


@SpringBootTest
@ActiveProfiles(`test`)
public class MyServiceTests {
  // Test logic here
}

55. Use @ConfigurationProperties for Binding Properties


@ConfigurationProperties(prefix = `my`)
public class MyProperties {
  private String name;
  // Getters and Setters
}

56. Use @EnableConfigurationProperties for Enabling Configuration Properties


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

57. Use @RestControllerAdvice for Global REST Exception Handling


@RestControllerAdvice
public class GlobalRestExceptionHandler {
  @ExceptionHandler(RuntimeException.class)
  public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
  }
}

58. Use @Cacheable for Caching Results


@Service
public class MyService {
  @Cacheable(`items`)
  public List<Item> getItems() {
    // Fetch items from database
  }
}

59. Use @CacheEvict for Evicting Cached Results


@Service
public class MyService {
  @CacheEvict(value = `items`, allEntries = true)
  public void clearCache() {
    // Clear cache logic
  }
}

60. Use @CachePut for Updating Cached Results


@Service
public class MyService {
  @CachePut(value = `items`, key = `#item.id`)
  public Item updateItem(Item item) {
    // Update item logic
  }
}

61. Use @Scheduled for Scheduling Tasks


@EnableScheduling
@Service
public class MyService {
  @Scheduled(fixedRate = 5000)
  public void scheduledTask() {
    // Task logic
  }
}

62. Use @Async for Asynchronous Execution


@EnableAsync
@Service
public class MyService {
  @Async
  public CompletableFuture<String> asyncMethod() {
    // Asynchronous logic
    return CompletableFuture.completedFuture(`Done`);
  }
}

63. Use @EnableScheduling for Scheduling Tasks


@Configuration
@EnableScheduling
public class SchedulerConfig {
  // Configuration logic
}

64. Use @EnableAsync for Asynchronous Execution


@Configuration
@EnableAsync
public class AsyncConfig {
  // Configuration logic
}

65. Use Spring Boot Starter for Web Applications


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

66. Use Spring Boot Starter for Data JPA


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

67. Use Spring Boot Starter for Security


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

68. Use Spring Boot Starter for Actuator


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

69. Use Spring Boot Starter for Testing


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

70. Use Spring Boot Starter for Thymeleaf


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

71. Use Spring Boot Starter for Mail


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

72. Use Spring Boot Starter for WebSocket


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

73. Use Spring Boot Starter for Batch Processing


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-batch</artifactId>
</dependency>

74. Use Spring Boot Starter for Data REST


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

75. Use Spring Boot Starter for Cloud


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter</artifactId>
</dependency>

76. Use Spring Boot Starter for OpenFeign


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

77. Use Spring Boot Starter for Config Client


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

78. Use Spring Boot Starter for Eureka Client


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-eureka-client</artifactId>
</dependency>

79. Use Spring Boot Starter for Ribbon


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>

80. Use Spring Boot Starter for Hystrix


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

81. Use Spring Boot Starter for Gateway


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

82. Use Spring Boot Starter for Security OAuth2


< dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

83. Use Spring Boot Starter for WebFlux


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

84. Use Spring Boot Starter for Reactive Data


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>

85. Use Spring Boot Starter for Redis


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

86. Use Spring Boot Starter for MongoDB


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

87. Use Spring Boot Starter for Cassandra


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>

88. Use Spring Boot Starter for Elasticsearch


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

89. Use Spring Boot Starter for JPA Hibernate


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

90. Use Spring Boot Starter for Thymeleaf


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

91. Use Spring Boot Starter for FreeMarker


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

92. Use Spring Boot Starter for Mustache


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mustache</artifactId>
</dependency>

93. Use Spring Boot Starter for WebSocket


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

94. Use Spring Boot Starter for Batch Processing


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-batch</artifactId>
</dependency>

95. Use Spring Boot Starter for Spring Cloud


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter</artifactId>
</dependency>

96. Use Spring Boot Starter for Spring Cloud Config


<dependency>
  <groupId>org.springframework ```html
.boot</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

97. Use Spring Boot Starter for Spring Cloud Netflix


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

98. Use Spring Boot Starter for Spring Cloud Gateway


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

99. Use Spring Boot Starter for Spring Cloud OpenFeign


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

100. Use Spring Boot Starter for Spring Cloud Circuit Breaker


<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.