Spring and Spring Boot Annotations Cheat Sheet
Spring and Spring Boot Annotations Cheat Sheet
Java Java API Spring Boot Python Python API SQL Kotlin C C++ C# Go R HTML JS CSS
Apache Kafka Cheat Sheet Spring Boot is developed on top of Spring Framework to simplify the configuration and deployment
process. It provides a set of defaults and auto-configuration options that allow developers to get
RabbitMQ Cheat Sheet
started quickly with minimal configuration. Spring Boot also includes an embedded web server,
Maven Commands Cheat Sheet making it easy to create standalone applications.
Docker Commands Cheat Sheet Here’s a handy cheat sheet of the most commonly used Spring and Spring Boot annotations:
Cheat Sheet for MySQL Database Special type of @Component for data repository classes. Enables
@Repository
Commands exception translation.
Cheat Sheet for PostgreSQL Special type of @Component for Spring MVC controllers that handle
Commands @Controller
web requests.
Cheat Sheet for MongoDB
Commands Combines @Controller and @ResponseBody. Handles web requests
@RestController
and returns JSON/XML responses directly.
SQL Commands Cheat Sheet
Automatically injects dependencies into a field, setter method, or
Oracle Database Commands Cheat @Autowired
Sheet constructor.
Microsoft SQL Server Commands Injects values from properties files into fields, setter methods, or
@Value
Cheat Sheet constructor parameters.
Cheat Sheet for GoF Design
Annotation Description
Patterns
HTTP Status Codes Cheat Sheet @Configuration Indicates that a class contains Spring bean definitions.
Cheat Sheet for HTTP Methods Declares a method that returns a Spring bean to be managed by the
@Bean
Apache Cassandra Cheat Sheet Spring container.
Redis Commands Cheat Sheet Automatically configures your Spring application based on the
@EnableAutoConfiguration
NetBeans Cheat Sheet dependencies present in the classpath.
Visual Studio Code (VSCode) Cheat Configures component scanning directives for use with
Sheet for Windows @ComponentScan @Configuration classes. Specifies base packages to scan for
Sublime Text Cheat Sheet for annotated components.
Windows
@RequestMapping Maps web requests to specific handler classes or handler methods.
Visual Studio Code (VSCode) Cheat
Sheet for macOS Shortcut for @RequestMapping(method = RequestMethod.GET).
@GetMapping
Handles GET requests.
Executors
@SessionAttributes Used to store model attributes in the session.
Functional interfaces
Binds a method parameter or method return value to a named model
Go bytes @ModelAttribute
attribute.
Go filepath
@Async Indicates that a method should be executed asynchronously.
Go fmt
Go os
@Profile Registers a bean only if a specified profile is active.
Go Programming
Go reflect
Go regexp
Annotation Description
Go slices
Creates a mock bean in a Spring application context (used with
Go sort @MockBean
Spring Boot for testing).
Go strconv
Creates a spy bean in a Spring application context (used with Spring
Go strings @SpyBean
Boot for testing).
Go time
HashSet Marks the main class of a Spring Boot application. Combines @Configuration,
@EnableAutoConfiguration, and @ComponentScan.
HTML Tutorial
IdentityHashMap
@SpringBootApplication
Iterator
public class MySpringBootApplication {
Java public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
Java Date and Time
}
Java Date Time }
Java Interview
Java Keywords
@Component
Java Lang
Marks a class as a Spring component, making it a managed bean.
Java Math
Java Methods
@Component
Java Programming
public class MyComponent {
Java Stream // Bean methods and properties
}
Java Util
JavaScript Tutorial
JUnit Tutorial
@Service
Kotlin Special type of @Component for service layer classes, typically containing business logic.
Kotlin Functions
Milestones
@Repository
Mockito Tutorial
Special type of @Component for data repository classes. Enables exception translation.
Module
MySQL Tutorial
@Repository
Number
public class MyRepository {
Object // Data access methods
Objects
}
Package
PriorityQueue @Controller
Python Array Special type of @Component for Spring MVC controllers that handle web requests.
Python Built-in Functions
Python OS @RestController
Python Programming public class MyRestController {
@GetMapping("/greet")
Python Random
public String greet() {
Python RE return "Hello, World!";
}
Python requests
}
Python statistics
Python String
@Autowired
Python SYS
Python threading Automatically injects dependencies into a field, setter method, or constructor.
R Programming
Spring Boot
// Use myService in methods
Spring Boot Tutorial }
Spring Framework
System
@Component
Thread public class MyComponent {
ThreadGroup @Value("${app.name}")
private String appName;
ThreadLocal
TreeMap
@Configuration
public class MyConfig {
Latest Posts @Bean
public MyService myService() {
Difference between HashMap and return new MyService();
LinkedHashMap in Java }
}
Difference between ArrayList and
HashSet in Java
Automatically configures your Spring application based on the dependencies present in the classpath.
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
@ComponentScan
Configures component scanning directives for use with @Configuration classes. Specifies base
packages to scan for annotated components.
@Configuration
@ComponentScan(basePackages = "com.example")
public class MyConfig {
// Configuration methods
}
@RequestMapping
@Controller
public class MyController {
@RequestMapping("/hello")
public String sayHello() {
return "hello";
}
}
@GetMapping
@RestController
public class MyRestController {
@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}
@PostMapping
@RestController
public class MyRestController {
@PostMapping("/create")
public String create(@RequestBody MyEntity entity) {
// Process entity
return "Created";
}
}
@PutMapping
Shortcut for @RequestMapping(method = RequestMethod.PUT). Handles PUT requests.
@RestController
public class MyRestController {
@PutMapping("/update")
public String update(@RequestBody MyEntity entity) {
// Update entity
return "Updated";
}
}
@DeleteMapping
@RestController
public class MyRestController {
@DeleteMapping("/delete/{id}")
public String delete(@PathVariable Long id) {
// Delete entity by id
return "Deleted";
}
}
@PatchMapping
@RestController
public class MyRestController {
@PatchMapping("/patch")
public String patch(@RequestBody MyEntity entity) {
// Patch entity
return "Patched";
}
}
@RequestParam
@RestController
public class MyRestController {
@GetMapping("/param")
public String param(@RequestParam String name) {
return "Hello, " + name;
}
}
@PathVariable
@RestController
public class MyRestController {
@GetMapping("/path/{id}")
public String path(@PathVariable Long id) {
return "ID: " + id;
}
}
@RequestBody
@RestController
public class MyRestController {
@PostMapping("/body")
public String body(@RequestBody MyEntity entity) {
return "Received: " + entity;
}
}
@ResponseBody
Indicates that the return value of a method should be used as the response body.
@Controller
public class MyController {
@RequestMapping("/json")
@ResponseBody
public String json() {
return "{\"message\":\"Hello, World!\"}";
}
}
@CrossOrigin
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyRestController {
@GetMapping("/cors")
public String cors() {
return "CORS Enabled";
}
}
@ExceptionHandler
@Controller
public class MyController {
@ExceptionHandler(Exception.class)
public String handleException() {
return "error";
}
}
@ControllerAdvice
Allows you to handle exceptions across the whole application, not just to an individual controller.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException() {
return "error";
}
}
@RestControllerAdvice
@RestControllerAdvice
public class GlobalRestExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException() {
return "{\"error\":\"An error occurred\"}";
}
}
@RequestScope
@Component
@RequestScope
public class MyRequestScopedBean {
// Bean methods and properties
}
@SessionScope
@Component
@SessionScope
public class MySessionScopedBean {
// Bean methods and properties
}
@ApplicationScope
@Component
@ApplicationScope
public class MyApplicationScopedBean {
// Bean methods and properties
}
@SessionAttributes
@Controller
@SessionAttributes("user")
public class MyController {
@ModelAttribute("user")
public User createUser() {
return new User();
}
}
@ModelAttribute
Binds a method parameter or method return value to a named model attribute.
@Controller
public class MyController {
@ModelAttribute("attribute")
public String addAttribute() {
return "value";
}
}
@Async
@Service
public class MyService {
@Async
public void asyncMethod() {
// Async method logic
}
}
@Scheduled
@Component
public class MyScheduledTask {
@Scheduled(cron = "0 0 * * * ?")
public void scheduledMethod() {
// Scheduled task logic
}
}
@EnableScheduling
@Configuration
@EnableScheduling
public class MyConfig {
// Configuration methods
}
@Conditional
@Configuration
public class MyConfig {
@Bean
@Conditional(MyCondition.class)
public MyService myService() {
return new MyService();
}
}
@Profile
@MockBean
Creates a mock bean in a Spring application context (used with Spring Boot for testing).
@SpringBootTest
public class MyTest {
@MockBean
private MyService myService;
@Test
public void test() {
// Test logic
}
}
@SpyBean
Creates a spy bean in a Spring application context (used with Spring Boot for testing).
@SpringBootTest
public class MyTest {
@SpyBean
private MyService myService;
@Test
public void test() {
// Test logic
}
}
Conclusion
Mastering Spring and Spring Boot annotations is essential for writing effective and efficient Java
applications. This cheat sheet provides a quick reference to the most commonly used annotations,
helping you streamline your development process and ensure your applications are well-structured
and maintainable.
By understanding and using these annotations effectively, you can simplify your configuration,
enhance your application’s functionality, and write cleaner code. Keep this guide handy to enhance
your productivity and make the most of Spring and Spring Boot. Happy coding!
Related Posts:
ANIL
AUGUST 13, 2024 AT 1:10 PM
Very useful
Reply
Leave a Comment
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
Post Comment