DEV Community

Isaac Tonyloi - SWE
Isaac Tonyloi - SWE

Posted on

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:

  • @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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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!";
    }
}
Enter fullscreen mode Exit fullscreen mode

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!";
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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> {
}
Enter fullscreen mode Exit fullscreen mode

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
dhanush9952 profile image
Dhanush

Annotations help you write cleaner, more concise code by eliminating the need for explicit configuration in XML files.

Few more annotations with explanations:

@SpringBootApplication

  • It is a class-level annotation. It is used to mark the main configuration class of a Spring Boot application. It is a meta-annotation.
  • This annotation combines three other annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan.
  1. @Configuration: Indicates that the class is a source of bean definitions for the application context.
  2. @EnableAutoConfiguration: Enables Spring Boot's auto-configuration mechanism, which automatically configures the Spring application based on dependencies present in the classpath.
  3. @ComponentScan: Tells Spring to scan the specified package and its sub-packages for components to register in the application context.

@Component

  • It is a class-level annotation used to indicate that a class is a Spring component.
  • It will automatically detect and register that class as a Spring bean in the application context.
  • This allows you to take advantage of Spring's dependency injection capabilities and easily manage the lifecycle of the bean.
  • It is a generic stereotype annotation in Spring that serves as a parent for more specific stereotype annotations like @Service, @Repository, and @Controller.
  • By using @Component, you are essentially declaring a class as a Spring-managed component without specifying a more specific stereotype.

@Autowired

  • It is used in Fields, Constructors and method-level to inject dependencies automatically.
  • It helps in achieving loose coupling between components by allowing Spring to manage the dependencies between beans.
  • It simplifies the process of wiring beans together and reduces the need for manual configuration.

@Scope("Singleton")

  • It is a class-level annotation, to define a bean as a singleton scoped bean.
  • By default, Spring beans are singletons if no scope is defined, meaning that only one instance of the bean is created and shared across the application context.

@Scope("Prototype")

  • It is a class-level annotation. It is used to define a bean as a prototype scoped bean.
  • This means that a new instance of the bean will be created every time it is injected or retrieved from the Spring container.

@Primary

  • It is a method-level annotation.
  • It used to indicate a primary bean when multiple beans of the same type are present in the Spring application context.

@Qualifier

  • It is a method-level annotation.
  • When multiple beans of same type are defined in the Spring application context, the @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.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@Component
public class Buy {
private Shop shop;
    @Autowired
    //public Buy(Shop shop){
    public Buy(@Qualifier("vegPizza") Shop shop){
    this.shop = shop;
    }

    public void buying() {
    shop.getPizza();
    }
}
    // Other methods in the service class
}
Enter fullscreen mode Exit fullscreen mode

@Configuration

  • It is a class-level annotation.
  • It is used to indicate that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.
  • Classes annotated with @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

  • It is a method-level annotation.
  • By annotating a method with @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
  • Beans defined using @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.
@Configuration   %% USED WITH CONFIGURATION %%
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyService();
    }
    @Bean
    public MyRepository myRepository() {
        return new MyRepository();
    }
}
Enter fullscreen mode Exit fullscreen mode

@Controller

  • It is a class level annotation.
  • This annotation marks the class as a Spring MVC controller, which means it can handle incoming HTTP requests.
  • It is used to map the data or model object to view or template and show it to the client.
  • We can use @ResponseBody annotation on individual methods to directly return data (e.g., JSON or XML) instead of a view.

@RestController

  • It is a specialized version of the @Controller annotation. It is known as Stereotype annotation.
  • When a method in a class annotated with @RestController returns an object, Spring automatically converts that object into JSON or XML response using message converters.
  • This eliminates the need for an additional @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

  • It can be used with both method level and class level of Controller class.
  • When annotated with method, it automatically maps the /Endpoint to AnyMethod() method defined under it.
  • When annotated with class, it acts as a common Pre-End-Point for the methods with /Endpoints.
  • Eg: /api/hello, where @RequestMapping("/api"), /api is annotated with class level.
@RestController
@RequestMapping("/api") %% CLASS LEVEL %%
public class ApiController {
   @RequestMapping(value="/hello", method=RequestMethod.GET) %% METHOD LEVEL %%
   @ResponseBody
    public String sayHello() {
        return "Hello from API!";
    }
Enter fullscreen mode Exit fullscreen mode

@ResponseBody

  • It is a method-level annotation.
  • When annotated with a method, it indicates that the return value of the method should be written directly to the HTTP response body.
  • It converts the object into JSON/XML and return data in JSON or XML formats.

@Service

  • It is a class-level annotation.
  • It is used to mark a Java class as a service layer component in the Spring application context.
  • By using the @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

  • It is a class-level annotation.
  • @Repository: Marks a class as a data access object (DAO) that interacts with a database.
  • It is a special type of DAO (Data Access Object) that provides an abstraction layer between the application and the data source.

@GetMapping

  • It is a method-level annotation.
  • It is used to map HTTP GET (retrieve) requests to specific handler methods in a controller class.
  • It is used to define the URL mapping for a specific controller method.
  • It is a specialized version of the @RequestMapping annotation, which is used to map HTTP requests to controller methods.
@Controller
public class UserController {
    @GetMapping("/users")   %% NO NEED method=RequestMethod.GET %%
    public String listUsers(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        return "users";
    }
}
Enter fullscreen mode Exit fullscreen mode

@PostMapping

  • It is a method-level annotation.
  • It is used to map HTTP POST requests to specific handler methods in a controller class.
  • It is a specialized version of the @RequestMapping annotation, which is used to map HTTP requests to controller methods.
@Controller
public class UserController {
    @PostMapping("/users")
    public ResponseEntity<User> createUser(@RequestBody User newUser) {
        // Create the user in the service layer
        User savedUser = userService.createUser(newUser);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
    }
}
Enter fullscreen mode Exit fullscreen mode

@putMapping

  • It is a method-level annotation.
  • It is used to map HTTP PUT (update) requests to specific handler methods in a controller class.
  • It is a specialized version of the @RequestMapping annotation, which is used to map HTTP requests to controller methods.
@Controller
public class UserController {
    @PutMapping("/users/{userId}")
    public ResponseEntity<User> updateUser(@PathVariable("userId") Long userId, @RequestBody User updatedUser) {
        // Update the user in the service layer
        User savedUser = userService.updateUser(userId, updatedUser);
        return ResponseEntity.ok(savedUser);
    }
}
Enter fullscreen mode Exit fullscreen mode

@DeleteMapping

  • It is a method-level annotation.
  • It is used to map HTTP DELETE requests to specific handler methods in a controller class.
  • It is used to define the URL mapping for a specific controller method that handles HTTP DELETE requests.
  • It is a specialized version of the @RequestMapping annotation, which is used to map HTTP requests to controller methods.
@Controller
public class UserController {
    @DeleteMapping("/users/{userId}")
    public ResponseEntity<Void> deleteUser(@PathVariable("userId") Long userId) {
        // Delete the user in the service layer
        userService.deleteUser(userId);
        return ResponseEntity.noContent().build();
    }
}
Enter fullscreen mode Exit fullscreen mode

@PathVariable

  • It is a method-parameter-level annotation. (used in method signature-before parameters)
  • It used to bind a method parameter to a URI template variable.
  • It is used to extract values from the URL path and use them in your controller method.
@GetMapping("/users/{userId}")
public User getUser(@PathVariable("userId") Long userId) {
    // Use the userId to fetch the user from the database
    return userService.getUserById(userId);
}
Enter fullscreen mode Exit fullscreen mode

@RequestParam

  • It is a method-level annotation.
  • It used to bind a method parameter to a request parameter.
  • It is used to extract values from the query string (the part of the URL after the ?) and use them in your controller method.
@GetMapping("/users")
public List<User> getUsers(@RequestParam("name") String name, @RequestParam("age") int age) {
    // Use the name and age parameters to fetch the users from the database
    return userService.getUsersByNameAndAge(name, age);
}
Enter fullscreen mode Exit fullscreen mode

@Query

  • It is a method-level annotation.
  • It is used to define custom queries for repository methods.
  • It is used to execute a custom SQL or JPQL (Java Persistence Query Language) query in your repository methods, instead of relying on the default query generation provided by Spring Data JPA.
public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.email = :email")
    User findByEmail(@Param("email") String email);
}
Enter fullscreen mode Exit fullscreen mode

@Param

  • It is a method parameter-level annotation.
  • It is used in conjunction with the @Query annotation to bind method parameters to query parameters.
  • This is particularly useful when you have dynamic query parameters that need to be passed to the query.
public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.email = :email AND u.name = :name")
    User findByEmailAndName(@Param("email") String email, @Param("name") String name);
}
Enter fullscreen mode Exit fullscreen mode

@OneToOne

  • It is field/property level annotation.
  • It is used to define a one-to-one relationship between two entity classes.