Commonly Used Spring Annotations
November 7, 2024About 1 min
Commonly Used Spring Annotations
1. @Component
- Marks a class as a Spring bean, allowing Spring to manage it.
- Can be used for general-purpose components.
@Component
public class MyComponent {
// class body
}
2. @Service
- A specialization of
@Component
, used for service layer classes. - Typically used for classes containing business logic.
@Service
public class MyService {
// service logic
}
3. @Repository
- A specialization of
@Component
, typically used for data access layers. - Marks a class as a repository (DAO), often interacting with a database.
@Repository
public class MyRepository {
// data access logic
}
4. @Controller
- A specialization of
@Component
, used to define web controllers in Spring MVC. - Typically used for handling HTTP requests in a Spring web application.
@Controller
public class MyController {
// handler methods
}
5. @RestController
- A specialized version of
@Controller
, includes@ResponseBody
by default. - Used for creating RESTful web services in Spring.
@RestController
public class MyRestController {
// REST API methods
}
6. @Qualifier
- Used with
@Autowired
to specify which bean to inject when multiple candidates exist.
@Autowired
@Qualifier("myService")
private MyService myService;
7. @Configuration
- Marks a class as a source of bean definitions.
- Used to define configuration classes in Java-based configuration.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
8. @Bean
- Defines a Spring bean inside a
@Configuration
class.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
9. @PathVariable
- Extracts values from the URI path.
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name) {
return "Hello, " + name;
}
10. @RequestParam
- Extracts query parameters from the request URL.
@GetMapping("/hello")
public String hello(@RequestParam String name) {
return "Hello, " + name;
}
11. @RequestBody
- Binds the HTTP request body to a method parameter in a controller.
- Used to handle JSON or XML data from the request body.
@PostMapping("/user")
public String createUser(@RequestBody User user) {
return "User created: " + user.getName();
}
12. @ExceptionHandler
- Handles exceptions in Spring MVC controllers.
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
return "error";
}