Introduction
This guide will provide a comprehensive cheat sheet for the most commonly used annotations in Spring and Spring Boot.
What is Spring Framework?
The Spring Framework is a comprehensive framework for building Java applications. It provides a wide range of functionalities, including dependency injection, transaction management, and aspect-oriented programming. Spring helps developers create high-performance, reusable, and easily testable code by managing the lifecycle and interactions of Java objects.
What is Spring Boot?
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 started quickly with minimal configuration. Spring Boot also includes an embedded web server, making it easy to create standalone applications.
Spring and Spring Boot Annotations Cheat Sheet
Here’s a handy cheat sheet of the most commonly used Spring and Spring Boot annotations:
Annotation | Description |
---|---|
@SpringBootApplication |
Marks the main class of a Spring Boot application. Combines @Configuration , @EnableAutoConfiguration , and @ComponentScan . This is where your application starts. |
@Component |
Marks a class as a Spring component, making it a managed bean. |
@Service |
Special type of @Component for service layer classes, typically containing business logic. |
@Repository |
Special type of @Component for data repository classes. Enables exception translation. |
@Controller |
Special type of @Component for Spring MVC controllers that handle web requests. |
@RestController |
Combines @Controller and @ResponseBody . Handles web requests and returns JSON/XML responses directly. |
@Autowired |
Automatically injects dependencies into a field, setter method, or constructor. |
@Value |
Injects values from properties files into fields, setter methods, or constructor parameters. |
@Configuration |
Indicates that a class contains Spring bean definitions. |
@Bean |
Declares a method that returns a Spring bean to be managed by the Spring container. |
@EnableAutoConfiguration |
Automatically configures your Spring application based on the dependencies present in the classpath. |
@ComponentScan |
Configures component scanning directives for use with @Configuration classes. Specifies base packages to scan for annotated components. |
@RequestMapping |
Maps web requests to specific handler classes or handler methods. |
@GetMapping |
Shortcut for @RequestMapping(method = RequestMethod.GET) . Handles GET requests. |
@PostMapping |
Shortcut for @RequestMapping(method = RequestMethod.POST) . Handles POST requests. |
@PutMapping |
Shortcut for @RequestMapping(method = RequestMethod.PUT) . Handles PUT requests. |
@DeleteMapping |
Shortcut for @RequestMapping(method = RequestMethod.DELETE) . Handles DELETE requests. |
@PatchMapping |
Shortcut for @RequestMapping(method = RequestMethod.PATCH) . Handles PATCH requests. |
@RequestParam |
Binds a web request parameter to a method parameter. |
@PathVariable |
Binds a URI template variable to a method parameter. |
@RequestBody |
Binds the body of a web request to a method parameter. |
@ResponseBody |
Indicates that the return value of a method should be used as the response body. |
@CrossOrigin |
Enables Cross-Origin Resource Sharing (CORS) on a method or class. |
@ExceptionHandler |
Defines a method to handle exceptions thrown by request handler methods. |
@ControllerAdvice |
Allows you to handle exceptions across the whole application, not just to an individual controller. |
@RestControllerAdvice |
Combines @ControllerAdvice and @ResponseBody . Applies to REST controllers. |
@RequestScope |
Indicates that a bean is request-scoped. |
@SessionScope |
Indicates that a bean is session-scoped. |
@ApplicationScope |
Indicates that a bean is application-scoped. |
@SessionAttributes |
Used to store model attributes in the session. |
@ModelAttribute |
Binds a method parameter or method return value to a named model attribute. |
@Async |
Indicates that a method should be executed asynchronously. |
@Scheduled |
Marks a method to be scheduled with a cron expression or fixed delay/rate. |
@EnableScheduling |
Enables support for scheduled tasks. |
@Conditional |
Registers a bean based on a condition. |
@Profile |
Registers a bean only if a specified profile is active. |
@MockBean |
Creates a mock bean in a Spring application context (used with Spring Boot for testing). |
@SpyBean |
Creates a spy bean in a Spring application context (used with Spring Boot for testing). |
Explanation with Code Snippets
@SpringBootApplication
Marks the main class of a Spring Boot application. Combines @Configuration
, @EnableAutoConfiguration
, and @ComponentScan
.
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
@Component
Marks a class as a Spring component, making it a managed bean.
@Component
public class MyComponent {
// Bean methods and properties
}
@Service
Special type of @Component
for service layer classes, typically containing business logic.
@Service
public class MyService {
// Business logic methods
}
@Repository
Special type of @Component
for data repository classes. Enables exception translation.
@Repository
public class MyRepository {
// Data access methods
}
@Controller
Special type of @Component
for Spring MVC controllers that handle web requests.
@Controller
public class MyController {
@RequestMapping("/hello")
public String sayHello() {
return "hello";
}
}
@RestController
Combines @Controller
and @ResponseBody
. Handles web requests and returns JSON/XML responses directly.
@RestController
public class MyRestController {
@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}
@Autowired
Automatically injects dependencies into a field, setter method, or constructor.
@Component
public class MyComponent {
@Autowired
private MyService myService;
// Use myService in methods
}
@Value
Injects values from properties files into fields, setter methods, or constructor parameters.
@Component
public class MyComponent {
@Value("${app.name}")
private String appName;
// Use appName in methods
}
@Configuration
Indicates that a class contains Spring bean definitions.
@Configuration
public class MyConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@Bean
Declares a method that returns a Spring bean to be managed by the Spring container.
@Configuration
public class MyConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@EnableAutoConfiguration
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
Maps web requests to specific handler classes or handler methods.
@Controller
public class MyController {
@RequestMapping("/hello")
public String sayHello() {
return "hello";
}
}
@GetMapping
Shortcut for @RequestMapping(method = RequestMethod.GET)
. Handles GET requests.
@RestController
public class MyRestController {
@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}
@PostMapping
Shortcut for @RequestMapping(method = RequestMethod.POST)
. Handles POST requests.
@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
Shortcut for @RequestMapping(method = RequestMethod.DELETE)
. Handles DELETE requests.
@RestController
public class MyRestController {
@DeleteMapping("/delete/{id}")
public String delete(@PathVariable Long id) {
// Delete entity by id
return "Deleted";
}
}
@PatchMapping
Shortcut for @RequestMapping(method = RequestMethod.PATCH)
. Handles PATCH requests.
@RestController
public class MyRestController {
@PatchMapping("/patch")
public String patch(@RequestBody MyEntity entity) {
// Patch entity
return "Patched";
}
}
@RequestParam
Binds a web request parameter to a method parameter.
@RestController
public class MyRestController {
@GetMapping("/param")
public String param(@RequestParam String name) {
return "Hello, " + name;
}
}
@PathVariable
Binds a URI template variable to a method parameter.
@RestController
public class MyRestController {
@GetMapping("/path/{id}")
public String path(@PathVariable Long id) {
return "ID: " + id;
}
}
@RequestBody
Binds the body of a web request to a method parameter.
@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
Enables Cross-Origin Resource Sharing (CORS) on a method or class.
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyRestController {
@GetMapping("/cors")
public String cors() {
return "CORS Enabled";
}
}
@ExceptionHandler
Defines a method to handle exceptions thrown by request handler methods.
@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
Combines @ControllerAdvice
and @ResponseBody
. Applies to REST controllers.
@RestControllerAdvice
public class GlobalRestExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException() {
return "{\"error\":\"An error occurred\"}";
}
}
@RequestScope
Indicates that a bean is request-scoped.
@Component
@RequestScope
public class MyRequestScopedBean {
// Bean methods and properties
}
@SessionScope
Indicates that a bean is session-scoped.
@Component
@SessionScope
public class MySessionScopedBean {
// Bean methods and properties
}
@ApplicationScope
Indicates that a bean is application-scoped.
@Component
@ApplicationScope
public class MyApplicationScopedBean {
// Bean methods and properties
}
@SessionAttributes
Used to store model attributes in the session.
@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
Indicates that a method should be executed asynchronously.
@Service
public class MyService {
@Async
public void asyncMethod() {
// Async method logic
}
}
@Scheduled
Marks a method to be scheduled with a cron expression or fixed delay/rate.
@Component
public class MyScheduledTask {
@Scheduled(cron = "0 0 * * * ?")
public void scheduledMethod() {
// Scheduled task logic
}
}
@EnableScheduling
Enables support for scheduled tasks.
@Configuration
@EnableScheduling
public class MyConfig {
// Configuration methods
}
@Conditional
Registers a bean based on a condition.
@Configuration
public class MyConfig {
@Bean
@Conditional(MyCondition.class)
public MyService myService() {
return new MyService();
}
}
@Profile
Registers a bean only if a specified profile is active.
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@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
}
}
Download Cheat Sheet
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!
Very useful