StackTipsStackTips

Most Commonly Used Annotations in Spring Boot

Spring Boot annotations are a form of metadata that provides data about a program that is not a part of the program itself. Following are some of the most used annotations in spring boot.

April 17, 2022 · 4 min read

Spring Boot Annotations are metadata that provides compile time or runtime instructions to spring to decide how to wire your application together. It follows convention over configuration principle rather than XML.

In the previous chapter, we saw several of these annotations in action while learning Dependency Injection. This chapter pulls them together into one quick reference guide, and we shall preview the ones you'll meet next as we start building APIs.

Stereotype and Bean Annotations (Recap)

These annotations register and wire up your beans — we covered each of them in detail in Chapter 4 and Chapter 5, so here's a quick reference table rather than a re-explanation:

AnnotationWhat it does
@SpringBootApplicationThis houses your main class. It combines @Configuration, @EnableAutoConfiguration, and @ComponentScan into one annotation.
@ComponentGeneric stereotype marking a class as a Spring-managed bean.
@ServiceA specialization of @Component for classes that hold business logic.
@RepositoryA specialization of @Component for classes that hold data persistence logic.
@ControllerA specialization of @Component for the presentation layer in Spring MVC. Spring provides another REST variant, @RestController used for API development.
@AutowiredTells Spring to inject an already-registered bean — on a field, constructor, or setter.
@ConfigurationMarks a class as a source of bean definitions.
@BeanUsed inside @Configuration class to register a custom Spring managed bean.

The @Controller, @Service, and @Repository annotations are all specializations of @Component annotation. Spring treats them the same way at registration time, but the distinct names help developers to identify purpose of a class at glance.

Here is how we can use the @Bean annotation to register a Spring managed bean:

@Configuration
public class AppConfig {
 
    @Bean
    public BeanExample beanExample() {
        return new BeanExample();
    }
}

Other Commonly Used Annotations

  • @Value — injects a value from your application.properties (or application.yml) file into a field, using ${property.name} syntax. We'll use this extensively in Chapter 7, Configuration Management.
@Value("${app.name}")
private String appName;
  • @PostConstruct — marks a method to run once, right after Spring has finished injecting all of a bean's dependencies. Useful for initialization logic that depends on those dependencies already being set:
@Service
public class UserService {
 
    @PostConstruct
    public void init() {
        System.out.println("UserService is ready to use.");
    }
}
  • @ControllerAdvice — marks a class that handles exceptions globally across all your @Controller/@RestController classes, instead of handling errors in every controller individually. We'll build one from scratch in Chapter 19, Centralized Error Handling.

Coming Up: Annotations for Building REST APIs

All of the annotations we have seen so far deal with wiring of spring beans. Let's shift our focus to some of the new set of annotation used for building REST APIs:

AnnotationWhat it's for
@RestControllerA @Controller that also assumes every method's return value should be written directly to the HTTP response body, as JSON.
@GetMapping, @PostMapping, @PutMapping, @DeleteMappingMap an HTTP method and URL path to a controller method.
@PathVariableBinds a value from the URL path (e.g., the 123 in /users/123) to a method parameter.
@RequestParamBinds a query-string parameter (e.g., ?page=2) to a method parameter.
@RequestBodyDeserializes the incoming JSON request body into a Java object.
@ValidTriggers bean validation on a @RequestBody or @PathVariable.

This isn't an exhaustive list of every annotation in Spring — there are many more — but these cover the ones you'll use regularly while building applications with Spring Boot.

Summary

In this chapter, we reviewed some of the most commonly used annotations and their uses. Also we have previewed the REST-specific annotations we're about to start using in the coming chapters.

In the next chapter, we'll dig into Configuration Management in Spring Boot, including a closer look at @Value and externalized configuration.


Related articles