@Component, @Service, @Repository and @Controller
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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)
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)); } }}otpGenerator is a bean? true plainHelper is a bean? false notifier is a bean? false
What this code does
- Only
OtpGeneratorbecame a bean: it is a normal class with@Component. PlainHelperhas no annotation, andNotifieris 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.
@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.
@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)
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); } }}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@Componentinside another annotation. It istruefor 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.
@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
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)); }}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-jdbcandcom.mysql:mysql-connector-jto di-lab'spom.xml, andspring.datasource.url=jdbc:mysql://localhost:3306/shoplitetoapplication.properties. No connection is opened, because nothing queries the database. Remove them again afterwards. ProductRepositoryandProductServiceare the classes from Example 2. The repository bean is a subclass that Spring generated (its name containsSpringCGLIB): 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
ProductRepositoryand 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.
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)
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()); }}UpiPaymentGateway -> [upi] GSTCalculator -> [GSTCalculator] OrderMailer -> [orderMailer] By name: UpiPaymentGateway
What this code does
@Component("upi")sets the name, sogetBean("upi")finds the gateway. The nameupiPaymentGatewaydoes not exist.GSTCalculatorstarts with two capitals and keeps its name.OrderMailergets the usual small first letter.getBeanNamesForTypereturns 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)
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 {}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 namepriceRules. Spring stops at startup; theCaused byline 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.
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)
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; }}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
InvoiceServiceasks for anInvoiceNumberGeneratorin its constructor (parameter 0), but that class has no annotation, so no such bean exists. Spring cannot buildInvoiceServiceand stops.- The fix: add
@Componentand its import toInvoiceNumberGenerator. It is a helper, not a layer, so plain@Componentfits 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,@Repositoryor@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 2Next step
Check your understanding
12 quick questions