🌱 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();
}
💡 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();
}
}
💡 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("@");
}
}
💡 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
}
}
💡 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> {}
💡 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
}
}
💡 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";
}
}
💡 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 |
Hi Dev.to contributors! We’re thrilled to announce We're offering your special Dev.to drop for our top content creators. Claim your rewards here (limited supply — act fast). – Admin