A Spring Boot application consists of several key annotations that configure components, enable auto-configuration, and manage dependency injection. Below is a comprehensive list of Spring Boot annotations categorized by their purpose.
1. Core Annotations (Bootstrapping & Configuration)
Annotation |
Description |
@SpringBootApplication |
Main entry point for a Spring Boot application. Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. |
@Configuration |
Marks a class as a Spring configuration class (equivalent to XML config). |
@ComponentScan |
Enables scanning for components (@Component, @Service, @Repository, etc.) in the package and sub-packages. |
@EnableAutoConfiguration |
Automatically configures Spring beans based on dependencies. (Part of @SpringBootApplication). |
Example
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApp.class, args);
}
}
2. Component Scanning & Stereotypes
Annotation |
Description |
@Component |
Generic annotation for Spring-managed beans. |
@Service |
Specialized @Component for business logic/service layer. |
@Repository |
Specialized @Component for data persistence (adds exception translation). |
@Controller |
Specialized @Component for Spring MVC controllers. |
@RestController |
Combination of @Controller and @ResponseBody, returning JSON/XML responses. |
Example
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String getMessage() {
return "Hello from MyService!";
}
}
3. Dependency Injection (DI)
Annotation |
Description |
@Autowired |
Injects dependencies automatically by type. |
@Qualifier |
Specifies which bean to inject when multiple candidates exist. |
@Primary |
Marks a bean as the default when multiple beans of the same type exist. |
@Bean |
Defines a Spring-managed bean inside a @Configuration class. |
Example: Dependency Injection
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyController {
private final MyService myService;
@Autowired // Injecting MyService bean
public MyController(MyService myService) {
this.myService = myService;
}
}
4. Bean Scope Management
Annotation |
Description |
@Scope("singleton") |
Default scope; only one instance is created. |
@Scope("prototype") |
A new instance is created for every request. |
@Scope("request") |
A new bean instance per HTTP request (for web apps). |
@Scope("session") |
A new bean per HTTP session (for web apps). |
Example
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype") // A new instance each time it is requested
public class PrototypeService { }
5. Spring MVC & REST API Annotations
Annotation |
Description |
@RequestMapping |
Maps HTTP requests to handler methods. |
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping |
Specialized versions of @RequestMapping for specific HTTP methods. |
@RequestBody |
Maps JSON/XML request body to a Java object. |
@ResponseBody |
Directly returns data (JSON/XML) instead of a view. |
@PathVariable |
Extracts values from the URL path. |
@RequestParam |
Extracts query parameters from a request. |
Example
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class MyRestController {
@GetMapping("/hello/{name}")
public String sayHello(@PathVariable String name) {
return "Hello, " + name;
}
}
6. Exception Handling
Annotation |
Description |
@ExceptionHandler |
Handles exceptions at the controller level. |
@RestControllerAdvice |
Global exception handling for all controllers. |
@ResponseStatus |
Specifies the HTTP status for an exception. |
Example
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleException(Exception ex) {
return "Error: " + ex.getMessage();
}
}
7. Transaction Management
Annotation |
Description |
@Transactional |
Marks a method or class as transactional (commits or rolls back transactions). |
Example
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class TransactionalService {
@Transactional
public void performTransaction() {
// Database operations here
}
}
8. Caching
Annotation |
Description |
@EnableCaching |
Enables Spring’s caching mechanism. |
@Cacheable |
Caches method results to improve performance. |
@CacheEvict |
Removes an entry from the cache. |
Example
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class CacheService {
@Cacheable("items")
public String getData(String key) {
return "Data for " + key;
}
}
9. Spring Security Annotations
Annotation |
Description |
@EnableWebSecurity |
Enables Spring Security. |
@Secured |
Restricts access based on roles. |
@PreAuthorize |
More advanced access control before method execution. |
Example
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class SecureService {
@PreAuthorize("hasRole('ADMIN')")
public String adminAccess() {
return "Admin Only";
}
}
10. Spring Boot Actuator Annotations
Annotation |
Description |
@EnableAutoConfiguration |
Enables Spring Boot’s auto-configuration features. |
@ConditionalOnProperty |
Enables a bean based on a property in application.properties. |
@ConditionalOnClass |
Enables a bean if a specific class is present in the classpath. |
Example
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public class FeatureBean { }
Conclusion
These are the most commonly used annotations in Spring Boot, covering configuration, dependency injection, REST APIs, transactions, security, caching, and more.
Comments
Post a Comment