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:
- @Configuration: Indicates that the class contains Spring configuration.
- @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration mechanism.
- @ComponentScan: Tells Spring to scan the package for components, configurations, and services.
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.
Top comments (1)
Annotations help you write cleaner, more concise code by eliminating the need for explicit configuration in XML files.
Few more annotations with explanations:
@SpringBootApplication
@Configuration
,@EnableAutoConfiguration
, and@ComponentScan
.@Configuration
: Indicates that the class is a source of bean definitions for the application context.@EnableAutoConfiguration
: Enables Spring Boot's auto-configuration mechanism, which automatically configures the Spring application based on dependencies present in the classpath.@ComponentScan
: Tells Spring to scan the specified package and its sub-packages for components to register in the application context.@Component
@Service
,@Repository
, and@Controller
.@Autowired
@Scope("Singleton")
@Scope("Prototype")
@Primary
@Qualifier
@Qualifier
annotation is used to specify which bean to be injected into a particular dependency.@Qualifier
helps resolve ambiguity when auto-wiring by name is not sufficient to uniquely identify the bean to be injected.@Configuration
@Bean
methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.@Configuration
can define methods annotated with@Bean
to create and configure beans. These beans are managed by the Spring container and can be injected into other components.@Configuration
promotes modularity and encapsulation by allowing you to group related bean definitions and configurations within a single class.@Bean
@Bean
, you are explicitly declaring that the return value of that method should be managed by the Spring container as a bean.@Bean
gives you more control over the instantiation and configuration of beans compared to component scanning or annotations like@Component
@Bean
can be injected into other Spring components using dependency injection by auto-wiring it.@Bean
is often used when integrating with external libraries or frameworks that require Spring beans to be created in a specific way.@Controller
@ResponseBody
annotation on individual methods to directly return data (e.g., JSON or XML) instead of a view.@RestController
@Controller
annotation. It is known as Stereotype annotation.@RestController
returns an object, Spring automatically converts that object into JSON or XML response using message converters.@ResponseBody
annotation on each method.@RestController
is a convenience annotation that combines@Controller
and@ResponseBody
, making it easier to write RESTful web services in Spring MVC.@RequestMapping
/Endpoint
toAnyMethod()
method defined under it./Endpoints
./api/hello
, where@RequestMapping("/api")
,/api
is annotated with class level.@ResponseBody
@Service
@Service
annotation, you can clearly separate the service layer logic from the other layers of your application, such as the controller and repository layers, promoting a clean and maintainable architecture.@Repository
@GetMapping
@RequestMapping
annotation, which is used to map HTTP requests to controller methods.@PostMapping
@putMapping
@RequestMapping
annotation, which is used to map HTTP requests to controller methods.@DeleteMapping
@RequestMapping
annotation, which is used to map HTTP requests to controller methods.@PathVariable
@RequestParam
@Query
@Param
@Query
annotation to bind method parameters to query parameters.@OneToOne