Spring Boot Annotations Explained: 15 Essential Annotations You Should Know

Spring Boot makes it incredibly easy to develop Java-based applications by abstracting much of the boilerplate configuration. One of the key features that make Spring Boot so powerful and user-friendly is its extensive use of annotations. These annotations help developers configure and manage their applications without writing large XML configuration files. In this article, we’ll explore 15 essential Spring Boot annotations that every developer should know.

1. @SpringBootApplication

This is the most important annotation in Spring Boot. It combines three key annotations:

Usage:

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

2. @RestController

This annotation is a shortcut for combining @Controller and @ResponseBody. It is used to create RESTful web services.

Usage:

@RestController
public class MyController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}

3. @RequestMapping

This annotation is used to map web requests to specific handler methods or classes. It can handle various HTTP methods like GET, POST, PUT, and DELETE.

Usage:

@RestController
@RequestMapping("/api")
public class ApiController {

    @RequestMapping(value = "/data", method = RequestMethod.GET)
    public String getData() {
        return "Here is the data!";
    }
}

4. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

These annotations are shortcuts for @RequestMapping for specific HTTP methods. They make the code more readable and focused.

Usage:

@GetMapping("/items")
public List<Item> getItems() {
    return itemService.getAllItems();
}

@PostMapping("/items")
public Item addItem(@RequestBody Item item) {
    return itemService.addItem(item);
}

5. @Autowired

This annotation is used to inject beans automatically by type. It can be used on constructors, setters, or fields.

Usage:

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

6. @Service

This annotation is used to mark a class as a service, which typically contains business logic. Spring automatically detects it and registers it as a bean.

Usage:

@Service
public class EmailService {
    public void sendEmail(String recipient, String message) {
        // logic for sending email
    }
}

7. @Repository

This annotation indicates that a class is a repository, which interacts with the database. It is a specialized version of @Component and provides automatic exception translation for database errors.

Usage:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

8. @Component

This generic annotation marks a class as a Spring-managed component. It is a core stereotype annotation that helps in automatic bean discovery.

Usage:

@Component
public class UtilityService {
    public String generateRandomString() {
        return UUID.randomUUID().toString();
    }
}

9. @Configuration

This annotation indicates that the class contains one or more Spring bean definitions. It’s used for configuration purposes.

Usage:

@Configuration
public class AppConfig {

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}

10. @Bean

This annotation is used to explicitly declare a Spring bean. It is typically used within @Configuration classes to define beans programmatically.

Usage:

@Configuration
public class AppConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

11. @EnableAutoConfiguration

This annotation is used to automatically configure Spring applications based on the classpath settings, other beans, and various property settings. Typically, this annotation is combined with @SpringBootApplication.

Usage:

@EnableAutoConfiguration
public class MyApplication {
    // Custom configuration code
}

12. @Qualifier

When multiple beans of the same type exist, @Qualifier is used to resolve the ambiguity by specifying which bean should be injected.

Usage:

@Service
public class NotificationService {

    @Autowired
    @Qualifier("emailService")
    private MessageService messageService;
}

13. @Value

This annotation is used to inject values from property files into Spring beans.

Usage:

@Component
public class AppProperties {

    @Value("${app.name}")
    private String appName;

    public String getAppName() {
        return appName;
    }
}

14. @Transactional

This annotation is used to indicate that a method or class should be wrapped in a database transaction. It ensures that operations within the transaction scope are atomic.

Usage:

@Service
public class PaymentService {

    @Transactional
    public void processPayment(Order order) {
        // payment processing logic
    }
}

15. @ExceptionHandler

This annotation is used to define a method that handles exceptions thrown by the controller. It allows for centralized error handling.

Usage:

@RestController
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Conclusion

Whether you’re building REST APIs, web applications, or microservices, Spring Boot annotations provide the power and flexibility to create robust, scalable applications with minimal effort.