Back to Bean Types & Stereotypes
Q4Question 4 of 5

What is @Component and how do stereotype annotations work in Spring

Answer: @Component is the generic Spring annotation that marks a class as a bean, and @Service, @Repository, and @Controller are specialized versions that add layer-specific behavior on top of the same bean registration.

Key Concepts
  • @Component is the base stereotype annotation that marks a class as a Spring-managed bean discovered during component scanning.
  • @Service, @Repository, and @Controller are specializations of @Component that carry the same bean registration behavior plus layer-specific semantics.
  • @Repository enables automatic exception translation, converting JDBC or JPA exceptions into Spring DataAccessException hierarchy.
  • @Controller marks a class as a Spring MVC controller, enabling @RequestMapping and view resolution; @RestController adds @ResponseBody to every method.
  • Choosing the correct stereotype communicates intent: @Service for business logic, @Repository for data access, @Controller for web endpoints.
  • All four annotations are meta-annotated with @Component, so @ComponentScan discovers them in exactly the same way.

Definition

@Component is the generic Spring annotation that marks a class as a bean, and @Service, @Repository, and @Controller are specialized versions that add layer-specific behavior on top of the same bean registration.
  • @Component is the base annotation that tells Spring to create an instance of this class and manage it as a bean in the application context.
  • @Service is a @Component specialization used in the service layer; it has no extra runtime behavior but documents that the class holds business logic.
  • @Repository is a @Component specialization used in the data access layer; it enables automatic exception translation from database-specific exceptions to Spring's DataAccessException.
  • @Controller is a @Component specialization used in the web layer; it enables Spring MVC features like @RequestMapping and view resolution.
  • @RestController is @Controller + @ResponseBody combined; every method return value is serialized directly to the HTTP response body as JSON.

Think of National Bank of India hiring employees. @Component is the generic employee badge that lets anyone enter the building. @Service is the badge for the loan processing department: same building access, but everyone knows this person handles business rules. @Repository is the badge for the vault room staff: same building access, plus a special alarm system (exception translation) that converts vault-specific errors into standard bank error codes. @Controller is the badge for the customer service desk: same building access, plus the ability to interact with customers walking through the front door (HTTP requests).

Understanding the Concepts

What is @Component?

@Component is the most basic Spring stereotype annotation. When you place @Component on a class, Spring's component scanner discovers it, creates an instance, and registers it as a bean in the application context.

Any class that does not fit neatly into the service, repository, or controller layer can use @Component. Utility classes, event listeners, and scheduled tasks are common uses.

JAVA
package com.bank.util;

import org.springframework.stereotype.Component;

@Component
public class TransactionIdGenerator {

    private long counter = 0;

    public String nextId() {
        counter++;
        return "TXN-" + String.format("%06d", counter);
    }
}
JAVA
package com.bank;

import com.bank.util.TransactionIdGenerator;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ComponentDemoApp {
    public static void main(String[] args) {
        SpringApplication.run(ComponentDemoApp.class, args);
    }

    @Bean
    CommandLineRunner demo(TransactionIdGenerator generator) {
        return args -> {
            System.out.println("ID 1: " + generator.nextId());
            System.out.println("ID 2: " + generator.nextId());
            System.out.println("ID 3: " + generator.nextId());
        };
    }
}
TEXT
Expected output:
ID 1: TXN-000001
ID 2: TXN-000002
ID 3: TXN-000003

How does @Service differ from @Component?

@Service is a @Component with a different name. If you open the source code of @Service, you see it is meta-annotated with @Component. At runtime, Spring treats both identically for bean registration.

The difference is semantic. @Service tells developers and tools that this class contains business logic. Static analysis tools like SonarQube can enforce layer rules: "@Service classes should not import @Controller classes."

Feature@Component@Service
Bean registrationYesYes (via @Component meta-annotation)
Discovered by @ComponentScanYesYes
Layer semanticsNone (generic)Business logic layer
Exception translationNoNo
Extra runtime behaviorNoneNone
Use caseUtility, helper, generic beanService layer, business rules
JAVA
package com.bank.service;

import org.springframework.stereotype.Service;
import java.math.BigDecimal;

@Service
public class InterestCalculatorService {

    private static final BigDecimal SAVINGS_RATE = new BigDecimal("0.04"); // 4% per year

    public BigDecimal calculateAnnualInterest(BigDecimal principal) {
        return principal.multiply(SAVINGS_RATE);
    }
}
JAVA
package com.bank;

import com.bank.service.InterestCalculatorService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.math.BigDecimal;

@SpringBootApplication
public class ServiceDemoApp {
    public static void main(String[] args) {
        SpringApplication.run(ServiceDemoApp.class, args);
    }

    @Bean
    CommandLineRunner demo(InterestCalculatorService calculator) {
        return args -> {
            var interest = calculator.calculateAnnualInterest(new BigDecimal("500000.00"));
            System.out.println("Annual interest on 500000 INR: " + interest + " INR");
        };
    }
}
TEXT
Expected output:
Annual interest on 500000 INR: 20000.00 INR

How does @Repository differ from @Component?

@Repository has the same bean registration behavior as @Component, but it adds one important runtime feature: automatic exception translation.

AnnotationLayerExtra behaviorUse case
@ComponentGenericNoneGeneral-purpose bean
@ServiceBusiness logicNone (semantic only)Service layer classes
@RepositoryData accessException translation (DataAccessException)DAO / repository classes
@ControllerWeb (MVC)View resolutionMVC controllers returning views
@RestControllerWeb (REST)@Controller + @ResponseBodyREST API endpoints

When a method in a @Repository class throws a database-specific exception (like SQLException, HibernateException, or JPA PersistenceException), Spring's PersistenceExceptionTranslationPostProcessor catches it and converts it to a Spring DataAccessException subclass. This means your service layer always catches the same exception hierarchy, regardless of whether you use JDBC, JPA, or MongoDB underneath.

JAVA
package com.bank.repository;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Repository
public class AccountRepository {

    private final Map<String, BigDecimal> store = new ConcurrentHashMap<>();

    public AccountRepository() {
        store.put("SAV2001", new BigDecimal("150000.00"));
        store.put("CUR3001", new BigDecimal("500000.00"));
    }

    public BigDecimal findBalance(String accountId) {
        BigDecimal balance = store.get(accountId);
        if (balance == null) {
            // In a real JPA repo, this would be a PersistenceException
            // @Repository ensures it becomes DataAccessException
            throw new IllegalArgumentException("Account not found: " + accountId);
        }
        return balance;
    }

    public void updateBalance(String accountId, BigDecimal newBalance) {
        store.put(accountId, newBalance);
    }
}
JAVA
package com.bank;

import com.bank.repository.AccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class RepoDemoApp {
    public static void main(String[] args) {
        SpringApplication.run(RepoDemoApp.class, args);
    }

    @Bean
    CommandLineRunner demo(AccountRepository repo) {
        return args -> {
            System.out.println("SAV2001 balance: " + repo.findBalance("SAV2001") + " INR");
            System.out.println("CUR3001 balance: " + repo.findBalance("CUR3001") + " INR");
            try {
                repo.findBalance("SAV9999");
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            }
        };
    }
}
TEXT
Expected output:
SAV2001 balance: 150000.00 INR
CUR3001 balance: 500000.00 INR
Error: Account not found: SAV9999

How does @Controller differ from @Component?

@Controller marks a class as a Spring MVC controller. The container registers it as a bean and also enables web-specific features: @RequestMapping, @GetMapping, @PostMapping, @PathVariable, @RequestParam, and view resolution.

@RestController is a convenience annotation that combines @Controller and @ResponseBody. With @RestController, every method return value is serialized to JSON (or XML) and written directly to the HTTP response body.

Feature@Controller@RestController
Bean registrationYesYes
@RequestMapping supportYesYes
View resolution (Thymeleaf, JSP)YesNo (returns body, not view)
@ResponseBody on every methodNo (must add manually)Yes (automatic)
Use caseServer-rendered HTML pagesREST API endpoints
JAVA
package com.bank.controller;

import com.bank.repository.AccountRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Map;

@RestController
public class AccountController {

    private final AccountRepository accountRepository;

    public AccountController(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @GetMapping("/accounts/{id}/balance")
    public Map<String, Object> getBalance(@PathVariable String id) {
        BigDecimal balance = accountRepository.findBalance(id);
        return Map.of(
            "accountId", id,
            "balance", balance,
            "currency", "INR"
        );
    }
}
TEXT
Expected output (curl http://localhost:8080/accounts/SAV2001/balance):
{"accountId":"SAV2001","balance":150000.00,"currency":"INR"}

What is a complete banking project using all stereotypes?

This project has a three-layer architecture: controller, service, repository. Each layer uses the correct stereotype annotation.

Project structure

DIAGRAM
bank-stereotype-demo/
├── pom.xml
└── src/
    ├── main/
    │   └── java/
    │       └── com/
    │           └── bank/
    │               ├── BankStereotypeDemoApp.java
    │               ├── model/
    │               │   └── Account.java
    │               ├── repository/
    │               │   └── AccountRepository.java
    │               ├── service/
    │               │   └── AccountService.java
    │               ├── controller/
    │               │   └── AccountController.java
    │               └── util/
    │                   └── TransactionIdGenerator.java
    └── test/
        └── java/
            └── com/
                └── bank/
                    └── service/
                        └── AccountServiceTest.java

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><parentsyn-kw">>
        syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
        syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
        syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
    syn-kw"></parentsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>bank-stereotype-demosyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
    syn-kw"></propertiessyn-kw">>

    syn-kw"><dependenciessyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-websyn-kw"></artifactIdsyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
    syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>

Account.java

JAVA
package com.bank.model;

import java.math.BigDecimal;

public record Account(
    String accountId,
    String holderName,
    BigDecimal balance,
    String type
) {}

TransactionIdGenerator.java (@Component)

JAVA
package com.bank.util;

import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class TransactionIdGenerator {
    private final AtomicLong counter = new AtomicLong(0);

    public String nextId() {
        return "TXN-" + String.format("%06d", counter.incrementAndGet());
    }
}

AccountRepository.java (@Repository)

JAVA
package com.bank.repository;

import com.bank.model.Account;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Repository
public class AccountRepository {

    private final Map<String, Account> store = new ConcurrentHashMap<>();

    @PostConstruct
    void init() {
        store.put("SAV2001", new Account("SAV2001", "Priya", new BigDecimal("150000.00"), "SAVINGS"));
        store.put("CUR3001", new Account("CUR3001", "Rajesh", new BigDecimal("500000.00"), "CURRENT"));
    }

    public Optional<Account> findById(String id) {
        return Optional.ofNullable(store.get(id));
    }

    public List<Account> findAll() {
        return List.copyOf(store.values());
    }
}

AccountService.java (@Service)

JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import com.bank.util.TransactionIdGenerator;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountService {

    private final AccountRepository accountRepository;
    private final TransactionIdGenerator idGenerator;

    public AccountService(AccountRepository accountRepository,
                          TransactionIdGenerator idGenerator) {
        this.accountRepository = accountRepository;
        this.idGenerator = idGenerator;
    }

    public Account getAccount(String id) {
        return accountRepository.findById(id)
            .orElseThrow(() -> new IllegalArgumentException("Account not found: " + id));
    }

    public List<Account> getAllAccounts() {
        return accountRepository.findAll();
    }

    public String generateTransactionId() {
        return idGenerator.nextId();
    }
}

AccountController.java (@RestController)

JAVA
package com.bank.controller;

import com.bank.model.Account;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/accounts")
public class AccountController {

    private final AccountService accountService;

    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping("/{id}")
    public Account getAccount(@PathVariable String id) {
        return accountService.getAccount(id);
    }

    @GetMapping
    public List<Account> getAllAccounts() {
        return accountService.getAllAccounts();
    }

    @GetMapping("/txn-id")
    public Map<String, String> getTransactionId() {
        return Map.of("transactionId", accountService.generateTransactionId());
    }
}

AccountServiceTest.java

JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import com.bank.util.TransactionIdGenerator;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;

class AccountServiceTest {

    private final AccountRepository repo = mock(AccountRepository.class);
    private final TransactionIdGenerator idGen = mock(TransactionIdGenerator.class);
    private final AccountService service = new AccountService(repo, idGen);

    @Test
    void getAccount_returnsAccount() {
        var account = new Account("SAV2001", "Priya", new BigDecimal("150000.00"), "SAVINGS");
        when(repo.findById("SAV2001")).thenReturn(Optional.of(account));

        Account result = service.getAccount("SAV2001");
        assertEquals("Priya", result.holderName());
        System.out.println("Test passed: found " + result.holderName());
    }

    @Test
    void getAccount_throwsForMissingAccount() {
        when(repo.findById("SAV9999")).thenReturn(Optional.empty());

        var ex = assertThrows(IllegalArgumentException.class,
            () -> service.getAccount("SAV9999"));
        assertEquals("Account not found: SAV9999", ex.getMessage());
        System.out.println("Test passed: " + ex.getMessage());
    }
}
TEXT
Expected output (curl http://localhost:8080/api/accounts/SAV2001):
{"accountId":"SAV2001","holderName":"Priya","balance":150000.00,"type":"SAVINGS"}

Expected output (curl http://localhost:8080/api/accounts/txn-id):
{"transactionId":"TXN-000001"}

How to run

BASH
cd bank-stereotype-demo
mvn clean package -DskipTests
java -jar target/bank-stereotype-demo-1.0.0.jar

# Test endpoints
curl http://localhost:8080/api/accounts/SAV2001
curl http://localhost:8080/api/accounts
curl http://localhost:8080/api/accounts/txn-id

# Run tests
mvn test

What are common mistakes with stereotype annotations?

Wrong: using @Component for everything

JAVA
package com.bank.service;

import org.springframework.stereotype.Component;

@Component  // WRONG: this is business logic, should be @Service
public class LoanApprovalService {
    public String approve(String accountId) {
        return "Loan approved for " + accountId;
    }
}
TEXT
Problem: @Component works, but it hides the class's role.
A developer reading the code cannot tell if this is a service, repository, or utility.
Tools like SonarQube and ArchUnit cannot enforce layer rules.
Future Spring features may add behavior based on @Service (like @Repository has exception translation).

Correct: use the right stereotype for the layer

JAVA
package com.bank.service;

import org.springframework.stereotype.Service;

@Service  // CORRECT: clearly marks this as business logic
public class LoanApprovalService {
    public String approve(String accountId) {
        return "Loan approved for " + accountId;
    }
}
TEXT
Correct: @Service tells developers and tools this is a service layer class.
ArchUnit can enforce: @Service classes should not depend on @Controller classes.
SonarQube can flag violations of layered architecture.

Wrong: using @Service on a data access class

JAVA
package com.bank.repository;

import org.springframework.stereotype.Service;

@Service  // WRONG: data access should be @Repository
public class TransactionRepository {
    public String findTransaction(String txnId) {
        // Simulates a database call
        return "TXN-" + txnId + ": 50000 INR debit";
    }
}
TEXT
Problem: @Service does not enable exception translation.
If findTransaction throws a JPA PersistenceException, it propagates as-is.
The service layer must catch vendor-specific exceptions instead of Spring's DataAccessException.

Correct: use @Repository for data access

JAVA
package com.bank.repository;

import org.springframework.stereotype.Repository;

@Repository  // CORRECT: enables exception translation
public class TransactionRepository {
    public String findTransaction(String txnId) {
        return "TXN-" + txnId + ": 50000 INR debit";
    }
}
TEXT
Correct: @Repository enables PersistenceExceptionTranslationPostProcessor.
JPA/Hibernate exceptions are converted to DataAccessException.
Service layer catches DataAccessException, not vendor-specific exceptions.

What about creating a custom stereotype annotation?

You can create your own stereotype by meta-annotating with @Component. This is useful when you have a category of beans that does not fit the standard stereotypes.

JAVA
package com.bank.annotation;

import org.springframework.stereotype.Component;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component  // This makes @Gateway a stereotype annotation
public @interface Gateway {
    String value() default "";
}
JAVA
package com.bank.gateway;

import com.bank.annotation.Gateway;

@Gateway
public class PaymentGatewayClient {
    public String charge(String accountId, String amount) {
        return "Charged " + amount + " INR to " + accountId + " via HDFC payment gateway";
    }
}
JAVA
package com.bank;

import com.bank.gateway.PaymentGatewayClient;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class CustomStereotypeApp {
    public static void main(String[] args) {
        SpringApplication.run(CustomStereotypeApp.class, args);
    }

    @Bean
    CommandLineRunner demo(PaymentGatewayClient gateway) {
        return args -> System.out.println(gateway.charge("SAV2001", "25000"));
    }
}
TEXT
Expected output:
Charged 25000 INR to SAV2001 via HDFC payment gateway

What should a senior or principal engineer know?

At the senior level, you should understand the internals of how stereotypes work and how to enforce architectural rules.

  • Meta-annotation mechanism: @Service, @Repository, and @Controller each have @Component on them. Spring's scanner checks for @Component recursively through meta-annotations. This is why custom stereotypes work.
  • Exception translation details: @Repository exception translation is done by PersistenceExceptionTranslationPostProcessor. It wraps the repository in an AOP proxy that catches persistence exceptions. If you use Spring Data JPA, this is already configured. For plain JDBC, you need the post-processor bean.
  • ArchUnit enforcement: use ArchUnit to enforce layer boundaries at test time. For example: classes in com.bank.repository must be annotated with @Repository, and classes in com.bank.service must not directly use @Controller classes.
  • Spring AOT and stereotypes: in GraalVM native images, Spring AOT generates reflection metadata for stereotype-annotated classes at compile time. Custom stereotypes work if they are meta-annotated with @Component.
  • Bean naming: by default, the bean name is the class name with a lowercase first letter. AccountService becomes "accountService". You can override it: @Service("paymentProcessor").
JAVA
package com.bank.core;

public class SeniorStereotypeKnowledge {
    public static void main(String[] args) {
        System.out.println("Senior/Principal Stereotype Checklist:");
        System.out.println("  1. All stereotypes are meta-annotated with @Component");
        System.out.println("  2. @Repository adds AOP proxy for exception translation");
        System.out.println("  3. PersistenceExceptionTranslationPostProcessor does the wrapping");
        System.out.println("  4. Use ArchUnit to enforce layer rules in tests");
        System.out.println("  5. Custom stereotypes: meta-annotate with @Component");
        System.out.println("  6. Bean name = class name with lowercase first letter");
        System.out.println("  7. Override name: @Service(\"customName\")");
        System.out.println("  8. Spring AOT handles stereotypes for native images");
    }
}
TEXT
Expected output:
Senior/Principal Stereotype Checklist:
  1. All stereotypes are meta-annotated with @Component
  2. @Repository adds AOP proxy for exception translation
  3. PersistenceExceptionTranslationPostProcessor does the wrapping
  4. Use ArchUnit to enforce layer rules in tests
  5. Custom stereotypes: meta-annotate with @Component
  6. Bean name = class name with lowercase first letter
  7. Override name: @Service("customName")
  8. Spring AOT handles stereotypes for native images

What are common interview follow-up questions?

  • Can you use @Component instead of @Service everywhere? (Yes, it compiles and works. But you lose layer semantics and future framework behavior tied to specific stereotypes.)
  • What happens if you forget @Repository on a JPA repository class? (Exception translation is not enabled. JPA PersistenceException propagates instead of Spring DataAccessException.)
  • What is the difference between @Controller and @RestController? (@RestController adds @ResponseBody to every method. @Controller returns view names by default.)
  • Can a class have both @Service and @Repository? (Technically yes, but it is a design mistake. A class should belong to one layer.)
  • How does Spring resolve the bean name from a stereotype annotation? (It lowercases the first letter of the class name. "AccountService" becomes "accountService". You can override it with the annotation's value attribute.)
  • Does @Service provide transaction management? (No. Transactions require @Transactional, which is separate from stereotypes.)

Visual Overview

DIAGRAM
 Stereotype Annotation Hierarchy
 =================================

                  ┌─────────────┐
                  │ @Component   │   Base annotation
                  │ (generic)    │   Bean registration only
                  └──────┬──────┘
           ┌─────────────┼─────────────┐
           │             │             │
           ▼             ▼             ▼
   ┌───────────┐ ┌────────────┐ ┌────────────┐
   │ @Service   │ │ @Repository│ │ @Controller│
   │            │ │            │ │            │
   │ Business   │ │ Data access│ │ Web layer  │
   │ logic      │ │ + exception│ │ + request  │
   │ layer      │ │ translation│ │ mapping    │
   └───────────┘ └────────────┘ └─────┬──────┘
                                      │
                                      ▼
                               ┌──────────────┐
                               │@RestController│
                               │               │
                               │ @Controller   │
                               │ + @ResponseBody│
                               └──────────────┘


 Three-Layer Architecture
 =========================

 ┌──────────────────────────────────┐
 │ @RestController                   │
 │ AccountController                 │  Web Layer
 │ GET /api/accounts/{id}            │
 └─────────────┬────────────────────┘
               │ calls
               ▼
 ┌──────────────────────────────────┐
 │ @Service                          │
 │ AccountService                    │  Service Layer
 │ getAccount(), getAllAccounts()     │
 └─────────────┬────────────────────┘
               │ calls
               ▼
 ┌──────────────────────────────────┐
 │ @Repository                       │
 │ AccountRepository                 │  Data Access Layer
 │ findById(), findAll()             │
 └──────────────────────────────────┘

Key Takeaway

@Component is the foundation of Spring's stereotype system. It marks a class as a Spring-managed bean. @Service, @Repository, and @Controller all extend @Component through meta-annotation, inheriting the same bean registration behavior while adding layer-specific semantics.

In our National Bank of India stereotype demo, we used @Component for TransactionIdGenerator (a utility), @Repository for AccountRepository (data access), @Service for AccountService (business logic), and @RestController for AccountController (web endpoints). Each annotation communicates the class's role in the architecture.

The key difference that matters at runtime is @Repository's exception translation. When a database call throws a vendor-specific exception, @Repository's AOP proxy converts it to Spring's DataAccessException. This lets the service layer catch a single exception type regardless of the underlying database technology.

Using the correct stereotype also enables tooling. ArchUnit can enforce that @Service classes do not directly depend on @Controller classes. SonarQube can flag misplaced stereotypes. Static analysis becomes possible because the annotations carry layer semantics.

At the senior level, understand that stereotypes work through meta-annotation (Spring checks for @Component recursively), that you can create custom stereotypes by meta-annotating with @Component, and that bean names default to the class name with a lowercase first letter.

Remember one sentence: @Component registers a bean, and @Service, @Repository, and @Controller are specialized versions that add layer semantics, with @Repository providing runtime exception translation.

---

Share
Use ← → arrow keys to navigate