Must-Know Annotations in Spring Boot with Examples π
4 min readDec 10, 2024
Annotations in Spring Boot simplify development by providing declarative support for configuring components, services, and application behaviors. Below is a comprehensive list of essential Spring Boot annotations with detailed explanations and practical examples.
π @SpringBootApplication
- Marks the main entry point of a Spring Boot application.
- Combines
@Configuration
,@EnableAutoConfiguration
, and@ComponentScan
. - Boots up the entire application with minimal configuration.
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
π @RestController
- Combines
@Controller
and@ResponseBody
to simplify building RESTful APIs. - Creates RESTful endpoints that return JSON or XML responses.
- Reduces boilerplate code when building APIs.
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob", "Charlie");
}
}
π @RequestMapping
- Maps HTTP requests to handler methods at the class or method level.
- Maps URLs to specific methods, supporting various HTTP methods like GET, POST, etc.
- Can be applied at both the class and method levels for better organization.
@RestController
@RequestMapping("/products")
public class ProductController {
@RequestMapping(value = "/all", method = RequestMethod.GET)
public List<String> getAllProducts() {
return List.of("Laptop", "Tablet", "Smartphone");
}
}
π @GetMapping, @PostMapping, @PutMapping, @DeleteMapping
- Specialized annotations for handling HTTP methods.
- Simplifies defining specific HTTP method mappings.
- Enhances readability compared to
@RequestMapping
.
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob", "Charlie");
}
@PostMapping("/users")
public String addUser(@RequestBody String user) {
return "User " + user + " added!";
}
@PutMapping("/users/{id}")
public String updateUser(@PathVariable int id, @RequestBody String user) {
return "User " + id + " updated to " + user;
}
@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable int id) {
return "User " + id + " deleted!";
}
}
π @Autowired
- Automatically wires Spring beans.
- Simplifies dependency injection by automatically resolving and injecting beans.
- Reduces boilerplate code for manual bean creation.
@Service
public class UserService {
public String getUserDetails() {
return "User Details";
}
}
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user")
public String getUser() {
return userService.getUserDetails();
}
}
π @Transactional
- Manages transactions to ensure data consistency.
- Used to roll back a database operation in case of exceptions.
- Ensures atomicity for multiple operations in a single transaction.
@Service
public class PaymentService {
@Transactional
public void processPayment() {
// Deduct amount from account A
// Add amount to account B
// If an error occurs, roll back the transaction
}
}
π @EnableCaching
- Enables caching capabilities in the application.
- Allows caching of frequently accessed data to improve performance.
- Works seamlessly with Springβs caching abstraction.
@SpringBootApplication
@EnableCaching
public class MyApplication {}
@Service
public class ProductService {
@Cacheable("products")
public List<String> getProducts() {
simulateDelay();
return List.of("Laptop", "Tablet", "Smartphone");
}
private void simulateDelay() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
π @Component
- Indicates a class is a Spring-managed component.
- Enables Spring to detect and instantiate the class during component scanning.
- Can be used for service, repository, or utility classes.
@Component
public class EmailService {
public void sendEmail(String message) {
System.out.println("Email Sent: " + message);
}
}
@RestController
public class NotificationController {
@Autowired
private EmailService emailService;
@GetMapping("/notify")
public String notifyUser() {
emailService.sendEmail("Hello User!");
return "Notification Sent!";
}
}
π @Service
- A specialized version of
@Component
used for service classes. - Denotes business logic or service layer components.
@Service
public class OrderService {
public String placeOrder(String item) {
return "Order placed for: " + item;
}
}
@RestController
public class OrderController {
@Autowired
private OrderService orderService;
@PostMapping("/order")
public String createOrder(@RequestBody String item) {
return orderService.placeOrder(item);
}
}
π @Repository
- A specialized version of
@Component
for DAO (Data Access Object) classes. - Encapsulates database operations and exception handling.
@Repository
public class UserRepository {
public List<String> findAllUsers() {
return List.of("Alice", "Bob", "Charlie");
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<String> getAllUsers() {
return userRepository.findAllUsers();
}
}
π @Bean
- Declares a method that returns a Spring-managed bean.
- Typically used in configuration classes to define custom beans.
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@RestController
public class ApiController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/api")
public String callExternalApi() {
return restTemplate.getForObject("https://api.example.com/data", String.class);
}
}
π @ConditionalOnProperty
- Configures beans based on the presence or value of a property.
- Enables conditional bean creation.
@Configuration
public class CacheConfig {
@Bean
@ConditionalOnProperty(name = "app.cache.enabled", havingValue = "true")
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("items");
}
}
π @Scheduled
- Triggers methods at fixed intervals or cron schedules.
- Useful for implementing periodic tasks like cleanup or notifications.
@Component
public class ReportScheduler {
@Scheduled(cron = "0 0 9 * * ?") // Runs daily at 9 AM
public void generateDailyReport() {
System.out.println("Generating Daily Report...");
}
}
π @Async
- Enables asynchronous method execution.
- Offloads tasks to a separate thread pool, improving scalability.
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean
public Executor taskExecutor() {
return new SimpleAsyncTaskExecutor();
}
}
@Service
public class NotificationService {
@Async
public void sendNotifications() {
System.out.println("Sending notifications...");
}
}
@RestController
public class NotificationController {
@Autowired
private NotificationService notificationService;
@GetMapping("/send")
public String send() {
notificationService.sendNotifications();
return "Notifications are being sent!";
}
}
π @Profile
- Activates beans based on the active Spring profile.
- Useful for environment-specific configurations like dev, test, or prod.
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public String devBean() {
return "Development Bean";
}
}
π @Value
- Injects property values into variables.
- Reads values from
application.properties
orapplication.yml
.
@RestController
public class AppController {
@Value("${app.name}")
private String appName;
@GetMapping("/app")
public String getAppName() {
return "Application Name: " + appName;
}
}
π @EventListener
- Listens for and handles application events.
- Supports custom and predefined Spring events.
@Component
public class UserEventListener {
@EventListener
public void handleUserCreatedEvent(UserCreatedEvent event) {
System.out.println("User Created: " + event.getUsername());
}
}
β β β β β β
Liked this article? If Yes follow me and subscribe to the codefarm YouTube channel.