Skip to lesson

@Component, @Service, @Repository and @Controller

A ShopLite app soon has dozens of classes: request handlers, business rules, database code and small helpers. Spring must find them all, and every reader must see at once which layer a class belongs to.

@Component: the general bean marker

A stereotype annotation, such as @Component, marks a class as a bean and says what role it plays. At startup Spring finds every annotated class and creates one bean from it.

Put @Component on a normal class and Spring makes a bean of it. A class with no annotation, and an interface, are skipped without any error. The runner asks the context which three became beans.

Example 1 · OtpGenerator.java, PlainHelper.java, Notifier.java, ScanCheckRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

OtpGenerator.javaJava
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class OtpGenerator {
    public String nextOtp() {        return "482913";    }}
package com.shoplite.lab;
// No annotation: Spring skips this classpublic class PlainHelper {}
package com.shoplite.lab;
import org.springframework.stereotype.Component;
// @Component on an interface: Spring cannot create an interface, so it skips it@Componentpublic interface Notifier {    void send(String message);}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;
@Componentpublic class ScanCheckRunner implements CommandLineRunner {
    private final ApplicationContext context;
    public ScanCheckRunner(ApplicationContext context) {        this.context = context;    }
    @Override    public void run(String... args) {        for (String name : new String[] {"otpGenerator", "plainHelper", "notifier"}) {            System.out.println(name + " is a bean? " + context.containsBean(name));        }    }}
Output
otpGenerator is a bean? true
plainHelper is a bean? false
notifier is a bean? false

What this code does

  • Only OtpGenerator became a bean: it is a normal class with @Component.
  • PlainHelper has no annotation, and Notifier is an interface, so Spring skipped both without any error. The mistake shows up later, when some class needs them.

At startup Spring searches the package of the main class and every package below it, a step called component scanning, and registers each annotated class it finds. The class must be one Spring can create: a normal class with a constructor Spring can call. An annotated interface cannot be turned into an object.

Without this marker, you would list every class by hand somewhere. With it, adding a class to the app is just writing the class.

Put stereotype annotations on classes, never on interfaces. Spring skips the interface without any warning.

@Service, @Repository and @Controller: same mechanism, clearer meaning

@Service, @Repository and @Controller are @Component with a more exact name, for business rules, data access and request handling. Spring gives them the same scanning, one shared bean and constructor injection.

Each of the three carries @Component on its own declaration, which is why Spring treats them alike. Here is how @Service is declared.

Java
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Component                    // this line makes @Service a @Componentpublic @interface Service {    @AliasFor(annotation = Component.class)    String value() default "";}

Example 2 · ProductRepository.java, ProductService.java, ProductController.java, LayerDemoRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

ProductRepository.javaJava
package com.shoplite.lab;
import java.math.BigDecimal;import java.util.Map;
import org.springframework.stereotype.Repository;
@Repositorypublic class ProductRepository {
    private final Map<String, BigDecimal> priceBySku = Map.of(            "BOOK-101", new BigDecimal("499.00"),            "PEN-007", new BigDecimal("25.00"));
    public BigDecimal findPrice(String sku) {        BigDecimal price = priceBySku.get(sku);        if (price == null) {            throw new IllegalArgumentException("Unknown SKU: " + sku);        }        return price;    }}
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
@Servicepublic class ProductService {
    private final ProductRepository repository;
    public ProductService(ProductRepository repository) {        this.repository = repository;    }
    public String priceLabel(String sku, int quantity) {        BigDecimal total = repository.findPrice(sku).multiply(BigDecimal.valueOf(quantity));        return quantity + " x " + sku + " = Rs " + total;    }}
package com.shoplite.lab;
import org.springframework.stereotype.Controller;
@Controllerpublic class ProductController {
    private final ProductService service;
    public ProductController(ProductService service) {        this.service = service;    }
    public void showPrice(String sku, int quantity) {        System.out.println(service.priceLabel(sku, quantity));    }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.core.annotation.AnnotatedElementUtils;import org.springframework.stereotype.Component;
@Componentpublic class LayerDemoRunner implements CommandLineRunner {
    private final ProductController controller;
    public LayerDemoRunner(ProductController controller) {        this.controller = controller;    }
    @Override    public void run(String... args) {        controller.showPrice("BOOK-101", 2);   // the runner plays the part of a browser here        controller.showPrice("PEN-007", 10);
        for (Class<?> type : new Class<?>[] {ProductRepository.class, ProductService.class, ProductController.class}) {            boolean isComponent = AnnotatedElementUtils.hasAnnotation(type, Component.class);            System.out.println(type.getSimpleName() + " counts as @Component? " + isComponent);        }    }}
Output
2 x BOOK-101 = Rs 998.00
10 x PEN-007 = Rs 250.00
ProductRepository counts as @Component? true
ProductService counts as @Component? true
ProductController counts as @Component? true

What this code does

  • Each layer has its stereotype, and each class receives the layer below it through the constructor: controller → service → repository.
  • di-lab has no web server, so the runner plays the browser and calls the controller. In shoplite-api, Spring MVC will call controllers for HTTP requests.
  • AnnotatedElementUtils.hasAnnotation(type, Component.class) also finds @Component inside another annotation. It is true for all three classes: they are all components.

The name tells people the layer. @Controller is for classes that take requests in, @Service for business rules, @Repository for code that stores and loads data. Plain @Component is for helpers that fit no layer, such as a price formatter.

In ShopLite every feature package uses all three: ProductController calls ProductService, which calls ProductRepository. In a web app Spring MVC also sends HTTP requests to @Controller classes; the next modules build that.

Order of execution

Follow one request through the layers

A customer asks for a product price. Put the steps in the order they happen.

@Repository's extra job: translating database exceptions

Exception translation turns the low-level errors of a database library into Spring's unchecked DataAccessException family, such as DuplicateKeyException. @Repository beans get it, so services do not depend on one database.

This service catches DuplicateKeyException when an email is already registered. It never mentions MySQL's own exception.

CustomerService.javaJava
@Servicepublic class CustomerService {
    private final CustomerRepository repository;   // constructor left out
    public void register(NewCustomer customer) {        try {            repository.insert(customer);        } catch (DuplicateKeyException e) {    // org.springframework.dao            throw new EmailAlreadyUsedException(customer.email(), e);        }    }}

Example 3 · src/main/java/com/shoplite/lab/ProxyCheckRunner.java

Runs in: di-lab with spring-boot-starter-jdbc and mysql-connector-j added

ProxyCheckRunner.javaJava
package com.shoplite.lab;
import org.springframework.aop.support.AopUtils;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class ProxyCheckRunner implements CommandLineRunner {
    private final ProductRepository repository;    private final ProductService service;
    public ProxyCheckRunner(ProductRepository repository, ProductService service) {        this.repository = repository;        this.service = service;    }
    @Override    public void run(String... args) {        System.out.println("Repository class: " + repository.getClass().getSimpleName());        System.out.println("Repository wrapped by Spring? " + AopUtils.isAopProxy(repository));        System.out.println("Service class: " + service.getClass().getSimpleName());        System.out.println("Service wrapped by Spring? " + AopUtils.isAopProxy(service));    }}
Output
Repository class: ProductRepository$$SpringCGLIB$$0
Repository wrapped by Spring? true
Service class: ProductService
Service wrapped by Spring? false

What this code does

  • To run it, add spring-boot-starter-jdbc and com.mysql:mysql-connector-j to di-lab's pom.xml, and spring.datasource.url=jdbc:mysql://localhost:3306/shoplite to application.properties. No connection is opened, because nothing queries the database. Remove them again afterwards.
  • ProductRepository and ProductService are the classes from Example 2. The repository bean is a subclass that Spring generated (its name contains SpringCGLIB): the proxy that translates exceptions. The service is your plain class.
  • Code that calls the repository does not notice the proxy: it still has type ProductRepository and every method works the same.

Once the app has Spring's data access support (spring-boot-starter-jdbc, or spring-boot-starter-data-jpa in Section 16), Spring Boot wraps each @Repository bean in a proxy, a Spring-made object that stands in front of yours and passes every call through. When JPA throws its own exception inside the repository, the proxy turns it into a DataAccessException. JdbcClient and JdbcTemplate, used in the last module, do this translation themselves.

The gain is in the service: it catches DuplicateKeyException, never MySQL's SQLIntegrityConstraintViolationException. Changing the database or the library later does not change the service.

The snippet is a preview: CustomerRepository, NewCustomer and EmailAlreadyUsedException are built in the ShopLite modules. Only @Service and DuplicateKeyException are Spring types.

Default bean names and custom names

A default bean name is the simple class name with the first letter made small, so OrderMailer becomes orderMailer. When the first two letters are both capitals the name stays as it is: GSTCalculator.

Three classes get bean names, one of them chosen with @Component("upi"). The runner prints the names Spring gave them.

Example 4 · UpiPaymentGateway.java, GSTCalculator.java, OrderMailer.java, BeanNameRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

UpiPaymentGateway.javaJava
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Component("upi")public class UpiPaymentGateway {}
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class GSTCalculator {}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class OrderMailer {}
package com.shoplite.lab;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;
@Componentpublic class BeanNameRunner implements CommandLineRunner {
    private final ApplicationContext context;
    public BeanNameRunner(ApplicationContext context) {        this.context = context;    }
    @Override    public void run(String... args) {        for (Class<?> type : new Class<?>[] {UpiPaymentGateway.class, GSTCalculator.class, OrderMailer.class}) {            String[] names = context.getBeanNamesForType(type);            System.out.println(type.getSimpleName() + " -> " + Arrays.toString(names));        }        System.out.println("By name: " + context.getBean("upi").getClass().getSimpleName());    }}
Output
UpiPaymentGateway -> [upi]
GSTCalculator -> [GSTCalculator]
OrderMailer -> [orderMailer]
By name: UpiPaymentGateway

What this code does

  • @Component("upi") sets the name, so getBean("upi") finds the gateway. The name upiPaymentGateway does not exist.
  • GSTCalculator starts with two capitals and keeps its name. OrderMailer gets the usual small first letter.
  • getBeanNamesForType returns every bean name for a type; here there is one each.

Example 5 · PriceRules.java, PriceRules.java

Runs in: the di-lab practice project (Spring Boot 4.1)

PriceRules.javaJava
package com.shoplite.lab.product;
import org.springframework.stereotype.Component;
@Componentpublic class PriceRules {}
package com.shoplite.lab.order;
import org.springframework.stereotype.Component;
@Componentpublic class PriceRules {}
Sample output (shortened)
2026-10-16T08:31:04.106+05:30 ERROR 29748 --- [di-lab] [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.shoplite.lab.DiLabApplication]
    ...
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'priceRules' for bean class [com.shoplite.lab.product.PriceRules] conflicts with existing, non-compatible bean definition of same name and class [com.shoplite.lab.order.PriceRules]

What this code does

  • Both classes are called PriceRules, so both want the bean name priceRules. Spring stops at startup; the Caused by line says which two classes clash.
  • Fix it with custom names, @Component("productPriceRules") and @Component("orderPriceRules"), or by renaming one class. Practice 6 does the first.

To pick the name yourself, pass it to the annotation: @Component("upi") or @Service("feeCalculator"). The class keeps its Java name; only the bean name changes.

Names matter when two classes share a simple name in different packages, for example product.PriceRules and order.PriceRules. Both want the bean name priceRules, and the app fails at startup with ConflictingBeanDefinitionException. Rename one class, or give each bean its own name.

Predict the output

Predict the bean names

Choose the bean name Spring gives.

Round 1 of 2

Two @Service classes with no custom name.

@Service
public class URLShortener { }
@Service
public class OtpService { }

Reading 'required a bean of type ... that could not be found'

The APPLICATION FAILED TO START report is what Spring Boot prints when the app cannot start. Its Description says which class needed which bean, and its Action suggests a fix.

InvoiceService asks for an InvoiceNumberGenerator that has no annotation. Start the app and read the report Spring Boot prints.

Example 6 · InvoiceNumberGenerator.java, InvoiceService.java

Runs in: the di-lab practice project (Spring Boot 4.1)

InvoiceNumberGenerator.javaJava
package com.shoplite.lab;
// Forgot @Componentpublic class InvoiceNumberGenerator {
    private int last = 1000;
    public String next() {        last++;        return "INV-" + last;    }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class InvoiceService {
    private final InvoiceNumberGenerator generator;
    public InvoiceService(InvoiceNumberGenerator generator) {        this.generator = generator;    }
    public String newInvoice(String customer) {        return generator.next() + " for " + customer;    }}
Sample output
2026-10-16T08:31:13.124+05:30 ERROR 32908 --- [di-lab] [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.shoplite.lab.InvoiceService required a bean of type 'com.shoplite.lab.InvoiceNumberGenerator' that could not be found.


Action:

Consider defining a bean of type 'com.shoplite.lab.InvoiceNumberGenerator' in your configuration.

What this code does

  • InvoiceService asks for an InvoiceNumberGenerator in its constructor (parameter 0), but that class has no annotation, so no such bean exists. Spring cannot build InvoiceService and stops.
  • The fix: add @Component and its import to InvoiceNumberGenerator. It is a helper, not a layer, so plain @Component fits best.
  • Your timestamp and process id will differ; the Description and Action text will match.

When a bean's constructor needs another bean that does not exist, the app does not start. Read the Description from the end: the type in quotes is the missing bean, and the class before it is the one that asked for it. The Action line says "Consider defining a bean"; for your own class that almost always means adding the right stereotype annotation.

Check the missing class in this order:

  • Does the class have @Component, @Service, @Repository or @Controller?
  • Is the annotation on the class, not on the interface it implements?
  • Is the class in the main class's package or a package below it?

Find the bug

Find the missing annotation

Each app fails with "required a bean ... that could not be found". Tap the wrong line.

InvoiceService needs this generator.

Round 1 of 2

Next step

Check your understanding

12 quick questions