DEV Community

Cover image for Spring Boot Annotation Guide
DrSimple
DrSimple

Posted on

Spring Boot Annotation Guide

🌱 Spring Boot Core Annotations Guide

This guide explains the most commonly used annotations in Spring Boot. Each annotation is presented with a clear definition, usage example, explanation, and tips on when to use it.


πŸ”§ @Bean

πŸ“ Definition:

Marks a method that returns a Spring-managed object (bean), also known as a Spring Managed Bean β€” an object created, configured, and managed by the Spring IoC container.

πŸ“Œ Usage:

Used inside a @Configuration class to define custom beans manually.

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Explanation:

The @Bean tells Spring:

  • β€œPlease call this method, and register the returned object (RestTemplate) as a bean in the application context.”
  • Anywhere you @Autowired RestTemplate, Spring will inject this same instance.

🧠 Why use it?

Use @Bean when:

  • You want full control over how the object is created.
  • You need to configure third-party classes (e.g., RestTemplate, ObjectMapper, etc.) that you can’t annotate with @Component.

πŸ—οΈ @Configuration

πŸ“ Definition:

Marks a class that defines one or more @Bean methods. It tells Spring this class contains bean definitions to be managed by the Spring container.

πŸ“Œ Usage:

Used to centralize bean creation using methods annotated with @Bean.

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Explanation:

  • Acts as a configuration blueprint for Spring.
  • Helps Spring manage lifecycle and dependencies of beans.

🧠 Why use it?

Use @Configuration when:

  • You want to define multiple beans manually.
  • You prefer Java-based configuration over XML.
  • You need conditional or advanced bean setup logic.

🧱 @Component

πŸ“ Definition:

Generic annotation to mark a class as a Spring-managed bean.

πŸ“Œ Usage:

Used on utility or helper classes that don’t fit into other stereotypes like @Service or @Repository.

@Component
public class EmailValidator {
    public boolean isValid(String email) {
        return email.contains("@");
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Explanation:

  • Automatically detected by Spring during component scanning.
  • Registered as a singleton bean in the context.

🧠 Why use it?

Use @Component when:

  • You want Spring to detect and manage a class automatically.
  • It’s a utility, config helper, or shared logic class.

🧠 @Service

πŸ“ Definition:

Specialization of @Component used to mark service-layer classes that contain business logic.

πŸ“Œ Usage:

Used for classes that implement business operations or domain logic.

@Service
public class PaymentService {
    public void processPayment() {
        // business logic
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Explanation:

  • Discovered by Spring during scanning.
  • Injected where needed for business operations.

🧠 Why use it?

Use @Service when:

  • The class holds core business logic.
  • You want clear separation between business and infrastructure layers.

πŸ—„οΈ @Repository

πŸ“ Definition:

Specialization of @Component for data access logic (DAO layer). Enables Spring's automatic exception translation.

πŸ“Œ Usage:

Used on classes or interfaces that interact with the database.

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Explanation:

  • Handles low-level persistence exceptions.
  • Translates JDBC/ORM exceptions to Spring's DataAccessException.

🧠 Why use it?

Use @Repository when:

  • You interact with the database.
  • You want Spring to handle exception translation.

🌐 @Controller

πŸ“ Definition:

Marks a class as a Spring MVC controller responsible for handling web requests and returning views.

πŸ“Œ Usage:

Used in MVC-based applications to return HTML (e.g., Thymeleaf, JSP).

@Controller
public class WebController {
    @GetMapping("/")
    public String home() {
        return "index"; // returns index.html
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Explanation:

  • Maps HTTP requests to methods.
  • Returns view names for rendering.

🧠 Why use it?

Use @Controller when:

  • Building a server-side rendered web app.
  • Returning HTML templates.

πŸ“‘ @RestController

πŸ“ Definition:

A convenience annotation that combines @Controller and @ResponseBody. Returns data (e.g., JSON) instead of views.

πŸ“Œ Usage:

Used for building RESTful API endpoints.

@RestController
public class ApiController {
    @GetMapping("/status")
    public String status() {
        return "OK";
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Explanation:

  • Treats all methods as if they had @ResponseBody.
  • Automatically serializes return values to JSON or XML.

🧠 Why use it?

Use @RestController when:

  • Building REST APIs.
  • Returning data instead of HTML.

🧾 Tip: @Component, @Service, @Repository, and @Controller are auto-detected via component scanning.

@Bean and @Configuration are used for manual bean definitions.

πŸ“‹ Spring Boot Annotations Summary

Annotation Layer/Type Purpose Auto-Detected Returns Data Usage Context
@Bean Configuration Declares a manually created Spring bean ❌ No βœ… Yes Used in @Configuration classes
@Configuration Configuration Declares a class containing @Bean definitions βœ… Yes ❌ No Java-based configuration
@Component Generic Bean Generic stereotype for any Spring-managed class βœ… Yes ❌ No Utility classes, general-purpose
@Service Service Layer Marks a class that holds business logic βœ… Yes ❌ No Business logic layer
@Repository Data Access DAO layer, adds exception translation for persistence βœ… Yes ❌ No Database access classes
@Controller Web MVC Handles web requests and returns HTML views βœ… Yes ❌ No Server-side rendered web apps
@RestController Web API (REST) Combines @Controller + @ResponseBody to return JSON/XML βœ… Yes βœ… Yes REST API endpoints

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.