🧩 Core Dependency Injection Annotations
1. @Component
What: @Component is a generic stereotype annotation for Spring-managed components.
Why: It automatically registers the class as a Spring bean.
Where: Placed on top of any Java class.
When to use: When you have a plain component that doesn’t belong to any specific layer.
@Component
public class EmailService {
public void send(String msg) {
System.out.println("Email: " + msg);
}
}
2. @Autowired
What: @Autowired injects dependencies automatically by type.
Why: Reduces boilerplate code in manual wiring of beans.
Where: Fields, constructors, or setter methods.
When to use: Whenever you need a Spring-managed dependency injected into another bean.
@Autowired
private EmailService emailService;
3. @Service
What: @service is specialized version of
@Component
for service layer beans.Why: Indicates the class holds business logic.
Where: On classes in the service layer.
When to use: When writing logic-heavy classes that don’t directly access data or handle web requests.
@Service
public class OrderService { }
4. @Repository
What: @Repository is specialized
@Component
for data access layer.Why: Enables Spring’s exception translation mechanism.
Where: DAO or repository classes.
When to use: When interacting with the database directly.
@Repository
public class UserRepository { }
5. @Controller
What: @Controller is marks a class as a web controller.
Why: Indicates that the class handles HTTP requests.
Where: On classes handling web page requests.
When to use: When using Spring MVC with traditional web pages.
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "index";
}
}
6. @RestController
What: @RestController is combines
@Controller
and@ResponseBody
.Why: Used for RESTful services to return JSON/XML.
Where: On REST API controller classes.
When to use: For REST APIs returning raw data (not views).
@RestController
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello";
}
}
🧭 Request Mapping Annotations
7. @RequestMapping
What: @RequestMapping Maps web requests to methods or classes.
Why: @RequestMapping acts as a universal request mapper.
Where: @RequestMapping annotation we have to use at the class or method level.
When to use: For custom mappings with more control (e.g., headers, methods).
@RequestMapping("/api")
public class ApiController {
@RequestMapping("/test")
public String test() { return "test"; }
}
8. @GetMapping
, @PostMapping
, @PutMapping
, @PatchMapping
, @DeleteMapping
What: Shorthand for
@RequestMapping(method=...)
Why: Improves code clarity and intent.
Where: On handler methods in controllers.
When to use: When handling HTTP requests in REST APIs.
@GetMapping("/get")
@PostMapping("/post")
@PutMapping("/put")
@PatchMapping("/patch")
@DeleteMapping("/delete")
9. @PathVariable
What: @PathVariable binds URI template variables to method parameters.
Why: @PathVariable extracts dynamic values from the URI.
Where: @PathVariable annotation we have to use as method parameters.
When to use: For RESTful routes like
/user/{id}
.
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") int id) { }
10. @RequestParam
What: Binds HTTP request query parameters to method parameters.
Why: To extract data from query strings.
Where: @RequestParam annotation we have to use as method parameters.
When to use: For query-based data like
/search?keyword=abc
.
@GetMapping("/search")
public String search(@RequestParam String keyword) { }
11. @RequestBody
What: Binds the body of the HTTP request to a method parameter.
Why: To map JSON/XML request bodies to Java objects.
Where: Method parameters.
When to use: For POST/PUT operations.
@PostMapping("/create")
public String create(@RequestBody User user) { }
12. @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) { }
13. @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) { }
14. @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) { }
15. @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
16. @Primary
What: Marks a bean as the primary candidate when multiple candidates are qualified to autowire.
Why: Prevents ambiguity when multiple beans of the same type exist.
Where: On a bean definition method or class.
When to use: When you want Spring to prefer a specific bean by default.
@Bean
@Primary
public NotificationService emailService() {
return new EmailNotificationService();
}
17. @Qualifier
What: Specifies which bean to inject when multiple candidates are present.
Why: Avoids ambiguity in autowiring.
Where: Along with
@Autowired
.When to use: When you have multiple beans of the same type.
@Autowired
@Qualifier("smsService")
private NotificationService notificationService;
18. @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(...) { }
19. @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 { }
20. @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) { ... }
21. @Bean
What: Declares a bean explicitly in Java config.
Why: Useful when defining 3rd-party beans or non-component beans.
Where: Inside
@Configuration
classes.When to use: When component scanning isn't an option.
@Bean
public MyService myService() {
return new MyServiceImpl();
}
22. @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;
23. @Value
What: Injects property values or expressions into Spring beans.
Why: Allows dynamic value injection.
Where: Fields, methods, or constructor parameters.
When to use: When reading values from
application.properties
or expressions.
@Value("${app.timeout}")
private int timeout;
🌐 JAX-RS Annotations (Java API for RESTful Web Services)
24. @GET
, @POST
, @PUT
, @DELETE
What: Specifies the HTTP method for a REST endpoint.
Why: Required in JAX-RS REST APIs.
Where: On resource methods.
When to use: When building REST APIs using JAX-RS (like Jersey).
@GET
@Path("/users")
public List<User> getUsers() { ... }
25. @Produces
, @Consumes
What: Specifies the MIME media types produced or consumed.
Why: Controls content negotiation.
Where: On resource classes or methods.
When to use: To define JSON/XML input-output formats.
@POST
@Consumes("application/json")
@Produces("application/json")
26. @Path
What: Binds a class or method to a specific URI path.
Why: Maps HTTP requests to specific JAX-RS resources.
Where: Resource classes and methods.
When to use: In JAX-RS-based APIs.
@Path("/api")
public class UserResource { }
27. @PathParam
, @QueryParam
What: Binds URI path/query parameters to method arguments.
Why: Enables data extraction from request URL.
Where: On method parameters.
When to use: In JAX-RS resources.
@GET
@Path("/user/{id}")
public User getUser(@PathParam("id") int id) { }
@GET
@Path("/search")
public List<User> search(@QueryParam("name") String name) { }
----------------------------------------
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 |
✅ Best Practice:
Use @PostMapping
when you're only handling a POST request. It's more readable and concise.
No comments:
Post a Comment