A Comprehensive Guide to Daily Used Annotations in Spring Boot
Spring Boot is a powerful framework for developing Java-based enterprise applications with minimal configuration. One of the key features that makes Spring Boot so developer-friendly is its extensive use of annotations. These annotations simplify coding, configuration, and management of application components.
This guide provides a detailed overview of the most commonly used annotations in Spring Boot, organized by categories. Each annotation is explained with examples to demonstrate its practical usage.
1. Core Annotations
1.1. @SpringBootApplication
- Purpose: Indicates that a class is the main entry point for a Spring Boot application.
- Details: Combines three annotations:
@Configuration
: Marks the class as a source of bean definitions.@EnableAutoConfiguration
: Enables Spring Boot’s auto-configuration mechanism.@ComponentScan
: Scans for components, configurations, and services in the package and sub-packages.
Example:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
1.2. @Component
- Purpose: Marks a Java class as a Spring-managed component.
- Details: Used to denote classes eligible for component scanning and dependency injection.
- Usage: Commonly used for service classes or utility classes.
Example:
@Component
public class MyService {
public String getMessage() {
return "Hello, Spring Boot!";
}
}
1.3. @Service
- Purpose: A specialization of
@Component
, specifically for the service layer. - Details: Indicates that a class provides business logic.
Example:
@Service
public class UserService {
public List<String> getAllUsers() {
return List.of("User1", "User2");
}
}
1.4. @Repository
- Purpose: Marks a class as a Data Access Object (DAO) and eligible for Spring DataException translation.
- Details: It is a specialization of
@Component
.
Example:
@Repository
public class UserRepository {
public List<String> findAll() {
return List.of("User1", "User2");
}
}
1.5. @Controller
and @RestController
- Purpose:
@Controller
is used to define a controller that handles web requests.@RestController
is a combination of@Controller
and@ResponseBody
. - Details:
@Controller
: Suitable for building traditional web applications (e.g., returning HTML views).
@RestController
: Ideal for REST APIs.
Example (Controller):
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
Example (RestController):
@RestController
public class ApiController {
@GetMapping("/api/greet")
public String greet() {
return "Hello, API!";
}
}
2. Dependency Injection and Bean Management
2.1. @Autowired
- Purpose: Automatically wires dependencies into a class.
- Details:
- Can be used on constructors, fields, or setter methods.
- Looks for a matching bean by type.
Example:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<String> getAllUsers() {
return userRepository.findAll();
}
}
2.2. @Qualifier
- Purpose: Resolves ambiguity when multiple beans of the same type are available.
- Details: Works with
@Autowired
.
Example:
@Service
public class NotificationService {
@Autowired
@Qualifier("emailService")
private Notification emailService;
}
2.3. @Bean
- Purpose: Defines a bean explicitly in a configuration class.
- Details: Used in conjunction with
@Configuration
.
Example:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
3. Web and REST Annotations
3.1. @RequestMapping
- Purpose: Maps HTTP requests to handler methods.
- Details:
- Can be applied at the class or method level.
- Supports attributes like
path
,method
, andparams
.
Example:
@RestController
@RequestMapping("/api")
public class ApiController {
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<String> getUsers() {
return List.of("User1", "User2");
}
}
3.2. Shortcut Annotations
- Purpose: Provide simpler alternatives to
@RequestMapping
for specific HTTP methods. - Details:
@GetMapping
: For HTTP GET.@PostMapping
: For HTTP POST.@PutMapping
: For HTTP PUT.@DeleteMapping
: For HTTP DELETE.@PatchMapping
: For HTTP PATCH.
Example:
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/users")
public List<String> getUsers() {
return List.of("User1", "User2");
}
@PostMapping("/users")
public String createUser() {
return "User created";
}
}
3.3. @PathVariable
- Purpose: Extracts values from the URL path.
- Details: Works with path parameters.
Example:
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/users/{id}")
public String getUser(@PathVariable("id") String id) {
return "User ID: " + id;
}
}
3.4. @RequestParam
- Purpose: Binds query parameters to method arguments.
- Details: Supports default values.
Example:
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/users")
public String getUser(@RequestParam(defaultValue = "Guest") String name) {
return "Hello, " + name;
}
}
3.5. @RequestBody
- Purpose: Maps the body of an HTTP request to a method parameter.
- Details: Used for JSON/XML request payloads.
Example:
@RestController
@RequestMapping("/api")
public class ApiController {
@PostMapping("/users")
public String createUser(@RequestBody User user) {
return "User created: " + user.getName();
}
}
3.6. @ResponseBody
- Purpose: Indicates that a method’s return value should be serialized directly into the HTTP response body.
- Details: Included in
@RestController
.
Example:
@Controller
public class ApiController {
@ResponseBody
@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}
4. Validation Annotations
4.1. @Valid
- Purpose: Validates an object based on constraints.
- Details: Used in conjunction with JSR-380 annotations like
@NotNull
,@Size
, etc.
Example:
@RestController
@RequestMapping("/api")
public class ApiController {
@PostMapping("/users")
public String createUser(@Valid @RequestBody User user) {
return "User is valid!";
}
}
4.2. Common JSR-380 Annotations
@NotNull
: Ensures a field is not null.@Size
: Specifies size constraints for a field.@Min
/@Max
: Specifies numeric range constraints.
Example:
public class User {
@NotNull
private String name;
@Min(18)
private int age;
// Getters and setters
}
5. Scheduling and Asynchronous Processing
5.1. @Scheduled
- Purpose: Schedules tasks to run periodically.
- Details: Requires
@EnableScheduling
.
Example:
@Component
public class TaskScheduler {
@Scheduled(fixedRate = 5000)
public void printMessage() {
System.out.println("Task executed every 5 seconds");
}
}
5.2. @Async
- Purpose: Marks a method for asynchronous execution.
- Details: Requires
@EnableAsync
.
Example:
@Service
public class AsyncService {
@Async
public void executeAsyncTask() {
System.out.println("Executing task asynchronously");
}
}
6. Security Annotations
6.1. @PreAuthorize
/ @PostAuthorize
- Purpose: Secures methods based on roles or conditions.
- Details: Requires Spring Security.
Example:
@Service
public class UserService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(String id) {
// Logic to delete user
}
}
6.2. @Secured
- Purpose: Restricts access to methods based on roles.
- Details: Similar to
@PreAuthorize
.
Example:
@Service
public class UserService {
@Secured("ROLE_ADMIN")
public void updateUser(String id) {
// Logic to update user
}
}
This guide covered the most frequently used Spring Boot annotations to assist developers in their day-to-day tasks. These annotations streamline the development process by reducing boilerplate code and enabling powerful functionality with minimal configuration.