Spring framework annotations

 In the Spring framework, various annotations are used to simplify development by providing different configurations, components, and functionalities. Below is a comprehensive list of the key Spring annotations across Spring Core, Spring Boot, and Spring MVC with their descriptions:

1. Spring Core Annotations:

These are the basic annotations used in Spring for dependency injection and configuration.

a) @Component

  • Marks a class as a Spring bean (i.e., it will be automatically registered in the application context).
@Component public class MyBean { // Your class definition }

b) @Service

  • A specialization of @Component to mark a service class, typically used in the service layer.
@Service public class MyService { // Service logic }

c) @Repository

  • A specialization of @Component used to define a DAO (Data Access Object) bean. It provides additional persistence-related functionality like exception translation.
@Repository public class ProductRepository { // Data access logic }

d) @Controller

  • Marks a class as a Spring MVC controller, typically used in web applications to handle HTTP requests.
@Controller public class MyController { // Controller logic }

e) @Autowired

  • Used for dependency injection. Spring automatically wires the bean by searching the context for the matching type.
@Autowired private MyService myService;

f) @Value

  • Injects values into fields from properties files or environment variables.
@Value("${app.name}") private String appName;

g) @Qualifier

  • Used in conjunction with @Autowired to specify which bean to inject when multiple beans of the same type exist.
@Autowired @Qualifier("myBean") private MyBean myBean;

h) @Bean

  • Defines a bean explicitly in a configuration class (usually used in @Configuration classes).
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }

i) @Configuration

  • Indicates that a class contains Spring configuration and bean definitions.
@Configuration public class AppConfig { // Bean definitions }

j) @Scope

  • Specifies the scope of a Spring bean (e.g., singleton, prototype, etc.).
@Scope("prototype") @Component public class MyBean { // Prototype scoped bean }

k) @PostConstruct

  • Marks a method to be called after the bean's properties are set, commonly used for initialization.
@PostConstruct public void init() { // Initialization logic }

l) @PreDestroy

  • Marks a method to be called before the bean is destroyed (clean-up logic).
@PreDestroy public void cleanup() { // Cleanup logic }

2. Spring Boot Annotations:

Spring Boot annotations simplify Spring application configuration and management.

a) @SpringBootApplication

  • A convenience annotation that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. It is used to mark the main class of a Spring Boot application.
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

b) @EnableAutoConfiguration

  • Tells Spring Boot to automatically configure the application based on the dependencies available in the classpath.
@EnableAutoConfiguration public class MyApplication { // Auto configuration will be applied }

c) @ComponentScan

  • Tells Spring to scan for components in the specified package. This is often used in conjunction with @SpringBootApplication.
@ComponentScan("com.example") public class MyApplication { // Scan for beans in the "com.example" package }

d) @ConfigurationProperties

  • Binds properties defined in application.properties or application.yml to a Java bean.
@ConfigurationProperties(prefix = "app") public class AppConfig { private String name; // Getters and setters }

e) @SpringBootTest

  • Used to write integration tests with Spring Boot, loading the full application context.
@SpringBootTest public class MyIntegrationTest { // Test logic }

f) @RestController

  • A convenience annotation that combines @Controller and @ResponseBody for creating REST APIs.
@RestController public class MyRestController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } }

g) @Value

  • Injects a value from application.properties or environment variables.
@Value("${app.name}") private String appName;

3. Spring MVC Annotations:

Spring MVC provides several annotations to handle web requests and responses.

a) @RequestMapping

  • Maps HTTP requests to handler methods of MVC controllers.
@RequestMapping("/home") public String homePage() { return "home"; }

b) @GetMapping

  • A shortcut for @RequestMapping(method = RequestMethod.GET) for GET requests.
@GetMapping("/products") public List<Product> getAllProducts() { return productService.getAllProducts(); }

c) @PostMapping

  • A shortcut for @RequestMapping(method = RequestMethod.POST) for POST requests.
@PostMapping("/products") public ResponseEntity<Product> addProduct(@RequestBody Product product) { return new ResponseEntity<>(productService.saveProduct(product), HttpStatus.CREATED); }

d) @PutMapping

  • A shortcut for @RequestMapping(method = RequestMethod.PUT) for PUT requests.
@PutMapping("/products/{id}") public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) { return new ResponseEntity<>(productService.updateProduct(id, product), HttpStatus.OK); }

e) @DeleteMapping

  • A shortcut for @RequestMapping(method = RequestMethod.DELETE) for DELETE requests.
@DeleteMapping("/products/{id}") public ResponseEntity<Void> deleteProduct(@PathVariable Long id) { productService.deleteProduct(id); return ResponseEntity.noContent().build(); }

f) @RequestParam

  • Used to extract query parameters from the request URL.
@GetMapping("/products") public List<Product> getProducts(@RequestParam String category) { return productService.getProductsByCategory(category); }

g) @PathVariable

  • Extracts values from the URI path.
@GetMapping("/products/{id}") public Product getProductById(@PathVariable Long id) { return productService.getProductById(id); }

h) @RequestBody

  • Binds the incoming HTTP request body to a method parameter.
@PostMapping("/products") public Product addProduct(@RequestBody Product product) { return productService.addProduct(product); }

i) @ResponseBody

  • Used to indicate that the return value of the method should be written directly to the HTTP response body (often used in REST controllers).
@ResponseBody public String hello() { return "Hello, World!"; }

j) @ModelAttribute

  • Binds request parameters to a model object, typically used in form handling
@ModelAttribute("product") public Product createProduct() { return new Product(); }

k) @ExceptionHandler

  • Handles exceptions thrown by request-handling methods.
@ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); }

Comments