✅ Spring Stereotype Annotations (for Component Scanning)
Annotation Purpose Applied On @ComponentGeneric stereotype for any Spring-managed component Class @ServiceSpecialization of @Component for service classes Service class @RepositorySpecialization of @Component for DAO layer Repository class @ControllerDefines a controller class in MVC Controller class @RestController@Controller + @ResponseBody (returns JSON/XML)REST API controller
| Annotation | Purpose | Applied On |
|---|---|---|
@Component | Generic stereotype for any Spring-managed component | Class |
@Service | Specialization of @Component for service classes | Service class |
@Repository | Specialization of @Component for DAO layer | Repository class |
@Controller | Defines a controller class in MVC | Controller class |
@RestController | @Controller + @ResponseBody (returns JSON/XML) | REST API controller |
1. @Component
@Component annotation marks a class as a Spring-managed component.
It is a generic stereotype for any Spring bean.
Detected automatically during component scanning.
It is parent annotation for @Service, @Repository, etc.@Component
public class EmailService {
public void send(String msg) {
System.out.println("Email: " + msg);
}
}
Detected automatically during component scanning.
It is parent annotation for
@Service, @Repository, etc.@Component
public class EmailService {
public void send(String msg) {
System.out.println("Email: " + msg);
}
}2. @Service
@service annotation is specialized version of @Component for service-layer classes.
And it supports features like transaction management.
@Service
public class OrderService { }3. @Repository
@Repository is specialized version of @Component for DAO classes.
It helps organize persistence logic in a clean way.
And it can be used with Spring Data JPA repositories.
@Repository
public class UserRepository { }4. @Controller
@Controller annotation is marks the class as a Spring MVC controller for handling web requests.
Typically returns view names that are resolved by ViewResolver.
It used in traditional Spring MVC applications.
And not suitable for REST APIs — for that, use @RestController.
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "index";
}
}
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "index";
}
}5. @RestController
@RestController annotation is that combines @Controller and @ResponseBody.
It is used to build RESTful web services that return JSON or XML directly.
It eliminates the need to annotate every method with @ResponseBody.
All methods in this class return response bodies, not view names.
@RestController
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello";
}
}
@RestController
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello";
}
}✅ Dependency Injection and Bean Lifecycle Annotations
Annotation Purpose @AutowiredAutomatically wires beans by type @QualifierResolves conflicts when multiple beans of same type exist @ValueInjects values from application.properties or application.yml @BeanDeclares a Spring bean in a @Configuration class @PrimaryGives a bean higher preference when multiple beans of same type exist @PostConstructLifecycle method that runs after bean is initialized @PreDestroyRuns before bean is destroyed
| Annotation | Purpose |
|---|---|
@Autowired | Automatically wires beans by type |
@Qualifier | Resolves conflicts when multiple beans of same type exist |
@Value | Injects values from application.properties or application.yml |
@Bean | Declares a Spring bean in a @Configuration class |
@Primary | Gives a bean higher preference when multiple beans of same type exist |
@PostConstruct | Lifecycle method that runs after bean is initialized |
@PreDestroy | Runs before bean is destroyed |
1. @Autowired
@Autowired annotation automatically injects dependencies by type.
It can be used on fields, constructors, or setter methods.
It simplifies dependency injection and removes the need for new.
If multiple candidates exist, use @Qualifier.
private EmailService emailService;
It can be used on fields, constructors, or setter methods.
It simplifies dependency injection and removes the need for
new.If multiple candidates exist, use
@Qualifier.private EmailService emailService;2. @Bean
Declares a bean manually inside a @Configuration class.
Returned object is managed by the Spring container.
Useful for third-party libraries or custom instantiations.
Provides full control over bean instantiation.
@Bean
public MyService myService() {
return new MyServiceImpl();
}
3.@PreDestroy
@PreDestroy is an annotation used in Spring to mark a method that should be executed just before a bean is destroyed,
typically during application shutdown. It is the cleanup phase of the bean lifecycle and allows releasing resources
like files, DB connections, or thread pools.
📦 Where It Comes From
It is part of the javax.annotation package, just like @PostConstruct.
✍️ Example Usage
@Component
public class CleanupService {
@PreDestroy
public void cleanup() {
System.out.println("Cleaning up before bean is destroyed.");
}
}
This method is called automatically when the Spring context is closed (e.g., app shutdown or context.close()).
🧠Use Cases
Closing database connections
Stopping background threads
Releasing resources (file handles, caches, etc.)
Flushing final logs or audit data
⚠️ Important Notes
Method must be void and take no arguments.
Method can be private, protected, or public.
Works only for Spring-managed beans with singleton scope (by default).
Not guaranteed to run on forceful shutdown (e.g., kill -9).
✅ Alternative: DisposableBean Interface
@Component
public class MyBean implements DisposableBean {
@Override
public void destroy() {
System.out.println("Cleaned up via DisposableBean.destroy()");
}
}
🛑 Application Shutdown Example
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
context.close(); // triggers @PreDestroy methods
}
4.@PostConstruct
@PostConstruct is an annotation used to mark a method that should be executed once immediately after bean initialization
(after dependency injection is done but before the bean is ready for use).
It comes from Java EE (javax.annotation.PostConstruct),but works in Spring as well.
Declares a bean manually inside a @Configuration class.
Returned object is managed by the Spring container.
Useful for third-party libraries or custom instantiations.
Provides full control over bean instantiation.
@Bean
public MyService myService() {
return new MyServiceImpl();
}
3.@PreDestroy
@PreDestroy is an annotation used in Spring to mark a method that should be executed just before a bean is destroyed,
typically during application shutdown. It is the cleanup phase of the bean lifecycle and allows releasing resources
like files, DB connections, or thread pools.
📦 Where It Comes From
It is part of the javax.annotation package, just like @PostConstruct.
✍️ Example Usage
@Component
public class CleanupService {
@PreDestroy
public void cleanup() {
System.out.println("Cleaning up before bean is destroyed.");
}
}
This method is called automatically when the Spring context is closed (e.g., app shutdown or context.close()).
🧠Use Cases
Closing database connections
Stopping background threads
Releasing resources (file handles, caches, etc.)
Flushing final logs or audit data
⚠️ Important Notes
Method must be void and take no arguments.
Method can be private, protected, or public.
Works only for Spring-managed beans with singleton scope (by default).
Not guaranteed to run on forceful shutdown (e.g., kill -9).
✅ Alternative: DisposableBean Interface
@Component
public class MyBean implements DisposableBean {
@Override
public void destroy() {
System.out.println("Cleaned up via DisposableBean.destroy()");
}
}
🛑 Application Shutdown Example
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
context.close(); // triggers @PreDestroy methods
}
4.@PostConstruct
@PostConstruct is an annotation used to mark a method that should be executed once immediately after bean initialization
(after dependency injection is done but before the bean is ready for use).
It comes from Java EE (javax.annotation.PostConstruct),but works in Spring as well.
5. @Primary
@Primary is a Spring annotation used to mark one bean as the default when multiple beans of the same type exist and no specific qualifier is provided.
It helps Spring resolve ambiguity during dependency injection.
⚙️ Why is it needed?
When there are multiple candidates for autowiring and you haven’t specified @Qualifier, Spring throws an exception unless one bean is marked as @Primary.
@Bean
@Primary
public NotificationService emailService() {
return new EmailNotificationService();
}
@Primary is a Spring annotation used to mark one bean as the default when multiple beans of the same type exist and no specific qualifier is provided.
It helps Spring resolve ambiguity during dependency injection.
⚙️ Why is it needed?
When there are multiple candidates for autowiring and you haven’t specified @Qualifier, Spring throws an exception unless one bean is marked as @Primary.
@Bean
@Primary
public NotificationService emailService() {
return new EmailNotificationService();
}
6. @Qualifier
Used with @Autowired to resolve bean conflicts.
Specifies which bean to inject when multiple candidates exist.
It matches the bean name with the qualifier name.
Avoids ambiguity in auto-wiring.
@Autowired
@Qualifier("smsService")
private NotificationService notificationService;
Used with @Autowired to resolve bean conflicts.
Specifies which bean to inject when multiple candidates exist.
It matches the bean name with the qualifier name.
Avoids ambiguity in auto-wiring.
@Autowired
@Qualifier("smsService")
private NotificationService notificationService;
7. @Value
injects values from application.properties or application.yml.
Can also be used to inject system properties or expressions.
Often used for URLs, port numbers, file paths, etc.
Supports SpEL (Spring Expression Language).
@Value("${app.timeout}")
private int timeout;
injects values from application.properties or application.yml.
Can also be used to inject system properties or expressions.
Often used for URLs, port numbers, file paths, etc.
Supports SpEL (Spring Expression Language).
@Value("${app.timeout}")
private int timeout;
8. @ModelAttribute
What: Binds form data to a model attribute.
Why: Supports data binding for web forms.
Where: Method parameters or methods.
When to use: In form submissions in MVC apps.
@PostMapping("/submit")
public String submit(@ModelAttribute User user) { }9. @SessionAttribute
What: Binds session attribute to a method parameter.
Why: Extracts data from HTTP session.
Where: Controller method parameters.
When to use: To access data persisted in session.
@GetMapping("/profile")
public String profile(@SessionAttribute("user") User user) { }10. @CookieValue
What: Binds a cookie value to a method parameter.
Why: Access cookies in controller methods.
Where: Method parameters.
When to use: When tracking state using cookies.
@GetMapping("/welcome")
public String welcome(@CookieValue("username") String user) { }11. @CrossOrigin
What: Enables Cross-Origin Resource Sharing (CORS).
Why: Allows frontends on different domains to access your API.
Where: On controller or method level.
When to use: With frontend-backend separation (like React + Spring Boot).
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/data")
public List<Data> getData() { }(## 🛠️ Bean Configuration and Customization Annotations
12. @Transactional
What: Declares a method or class to be transactional.
Why: Automatically manages database transaction boundaries.
Where: Service methods or classes.
When to use: For any DB operation that should follow ACID principles.
@Transactional
public void transferMoney(...) { }13. @Scope
What: Defines the scope of a Spring bean.
Why: To control the lifecycle and visibility (singleton, prototype, etc.).
Where: On bean definition classes.
When to use: When you need a bean to have non-singleton behavior.
@Component
@Scope("prototype")
public class ShoppingCart { }14. @Required
What: Marks a setter method as required.
Why: Tells Spring to fail if the dependency is not set.
Where: Setter methods.
When to use: When a bean cannot work without a particular dependency.
@Required
public void setDataSource(DataSource ds) { ... }15. @Lazy
What: Marks a bean for lazy initialization.
Why: Helps optimize startup by delaying bean creation.
Where: On bean classes or definitions.
When to use: For rarely used beans or circular dependencies.
@Lazy
@Autowired
private HeavyComponent heavyComponent;✅ Web Layer Annotations
Annotation Purpose Example @GetMapping, @PostMapping, @PutMapping, @DeleteMappingMaps HTTP methods to controller methods @GetMapping("/users")@RequestMappingGeneric mapping annotation (for any HTTP method) @RequestMapping("/api")@PathVariableBinds URI path variables to method params @GetMapping("/user/{id}")@RequestParamBinds query parameters to method params /search?name=John@RequestBodyBinds request body to a POJO Used in POST/PUT @ResponseBodyIndicates the return value is the HTTP response body Mostly auto-included in @RestController
| Annotation | Purpose | Example |
|---|---|---|
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping | Maps HTTP methods to controller methods | @GetMapping("/users") |
@RequestMapping | Generic mapping annotation (for any HTTP method) | @RequestMapping("/api") |
@PathVariable | Binds URI path variables to method params | @GetMapping("/user/{id}") |
@RequestParam | Binds query parameters to method params | /search?name=John |
@RequestBody | Binds request body to a POJO | Used in POST/PUT |
@ResponseBody | Indicates the return value is the HTTP response body | Mostly auto-included in @RestController |
1. @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping
Shortcut annotations for HTTP request mapping (introduced in Spring 4.3+).
They map GET, POST, PUT, DELETE, and PATCH requests specifically.
Cleaner and more expressive than using @RequestMapping(method = ...).
Common in REST controllers.
@GetMapping("/get")
@PostMapping("/post")
@PutMapping("/put")
@PatchMapping("/patch")
@DeleteMapping("/delete")
Shortcut annotations for HTTP request mapping (introduced in Spring 4.3+).
They map GET, POST, PUT, DELETE, and PATCH requests specifically.Cleaner and more expressive than using
@RequestMapping(method = ...).Common in REST controllers.
@GetMapping("/get")
@PostMapping("/post")
@PutMapping("/put")
@PatchMapping("/patch")
@DeleteMapping("/delete")2. @RequestMapping
@RequestMapping annotation is maps HTTP requests to specific controller methods.
It can be used at both class and method level.
And it supports all HTTP methods (GET, POST, PUT, DELETE, etc.).
And it used in common in both REST and MVC controllers.
@RequestMapping("/api")
public class ApiController {
@RequestMapping("/test")
public String test() { return "test"; }
}
@RequestMapping annotation is maps HTTP requests to specific controller methods.
It can be used at both class and method level.And it supports all HTTP methods (GET, POST, PUT, DELETE, etc.).
And it used in common in both REST and MVC controllers.
@RequestMapping("/api")
public class ApiController {
@RequestMapping("/test")
public String test() { return "test"; }
}3. @PathVariable
@PathVariable is used to bind URI path parameters to method arguments.
It helps extract values from the URL (e.g., /user/{id}).
It often used in REST APIs for dynamic path handling.
It can also specify if the variable is required.
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") int id) { }
@PathVariable is used to bind URI path parameters to method arguments.
It helps extract values from the URL (e.g., /user/{id}).
It often used in REST APIs for dynamic path handling.
It can also specify if the variable is required.
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") int id) { }4. @RequestParam
@RequestParam is used to extract query parameters from the request URL.It maps HTTP request parameters to method parameters.
It is common in search or filter endpoints.
And it supports default values and optional parameters.
@GetMapping("/search")
public String search(@RequestParam String keyword) { }
@RequestParam is used to extract query parameters from the request URL.It is common in search or filter endpoints.
And it supports default values and optional parameters.
@GetMapping("/search")
public String search(@RequestParam String keyword) { }5. @RequestBody
Binds the request body to a Java object automatically.
It typically used in POST or PUT methods to receive JSON/XML.
Spring converts the payload using HttpMessageConverters.
Ensures structured data input in REST APIs.
@PostMapping("/create")
public String create(@RequestBody User user) { }
6.@ResponseBody
Indicates the return value of a method should be written to the response body.
Spring uses it to convert Java objects to JSON or XML.
Used with @Controller, or is implied by @RestController.
Avoids returning a view name.
It typically used in POST or PUT methods to receive JSON/XML.
Spring converts the payload using
HttpMessageConverters.Ensures structured data input in REST APIs.
@PostMapping("/create")
public String create(@RequestBody User user) { }6.@ResponseBodyIndicates the return value of a method should be written to the response body.
Spring uses it to convert Java objects to JSON or XML.
Used with @Controller, or is implied by @RestController.
Avoids returning a view name.✅ Spring Data & JPA Annotations
Annotation Purpose @EntityMarks a class as a JPA entity @IdSpecifies the primary key field @GeneratedValueAuto-generates primary key values @ColumnCustomizes column mapping @RepositoryIndicates DAO layer component
| Annotation | Purpose |
|---|---|
@Entity | Marks a class as a JPA entity |
@Id | Specifies the primary key field |
@GeneratedValue | Auto-generates primary key values |
@Column | Customizes column mapping |
@Repository | Indicates DAO layer component |
✅ Spring Boot Feature Enabling Annotations
Annotation Purpose @EnableCachingEnables caching mechanism @EnableSchedulingEnables scheduled tasks via @Scheduled @EnableAsyncEnables asynchronous execution with @Async @EnableJpaRepositoriesEnables Spring Data JPA repositories @EnableTransactionManagementEnables transaction support
| Annotation | Purpose |
|---|---|
@EnableCaching | Enables caching mechanism |
@EnableScheduling | Enables scheduled tasks via @Scheduled |
@EnableAsync | Enables asynchronous execution with @Async |
@EnableJpaRepositories | Enables Spring Data JPA repositories |
@EnableTransactionManagement | Enables transaction support |
--------------------------------
In Spring (especially Spring Boot), both @PostMapping and @RequestMapping with method POST are used to handle HTTP POST requests. However, they differ slightly in syntax and usage.
✅ 1. @PostMapping (Shortcut Annotation)
Introduced in Spring 4.3+.
A specialized version of
@RequestMapping.Used only for POST requests.
Cleaner and more expressive.
✅ 2. @RequestMapping(method = RequestMethod.POST)
More generic.
Used when you need to support multiple HTTP methods.
Slightly more verbose.
| Feature | @PostMapping | @RequestMapping(method = POST) |
|---|---|---|
| Introduced in | Spring 4.3 | Spring 2.5 |
| Purpose | Specific to POST | Generic — supports all HTTP methods |
| Verbosity | Less verbose | More verbose |
| Readability | Better for POST-only | Useful for multiple method mappings |
No comments:
Post a Comment