Stereotypes and component scan

Junior Always asked 6 min

On this page

The question

What is the difference between @Component, @Service, @Repository and @Controller?

30-second answer

All four make a class a bean, because the last three are themselves annotated with @Component, so the scan finds them the same way. The difference is meaning and a little behavior. @Service adds nothing but intent. @Repository translates persistence exceptions into DataAccessException. @Controller is what Spring MVC (Model-View-Controller) maps URLs to.

Understand it

The stereotype family

Tap the parts

Select a part to see what it does.

Tap a stereotype. Each row shows which annotation it carries and what it adds on top.

View as text

Six rows, one per stereotype. Each has a button with the annotation, the annotation it carries, and what it adds.

@Component: The root. Found by the scan. Marks any class as a bean. The scan finds it, and the container creates and wires it. Every stereotype below carries this annotation, so all of them are found the same way.

@Service: Is a @Component. Adds no behavior. Says this class holds business logic. Spring adds nothing to it today, so swapping it for @Component changes no behavior. It documents intent, and pointcuts can target it.

@Repository: Is a @Component. Translates exceptions. Says this class accesses data. It is the one with real behavior: a database or JPA exception is translated into a DataAccessException, such as DataIntegrityViolationException, so callers do not depend on the vendor.

@Controller: Is a @Component. Handles web requests. Says this class handles web requests. Spring MVC looks for it when it maps URLs to methods. By default a returned String is a view name, not a response body.

@RestController: Is a @Controller. Adds @ResponseBody. A @Controller plus @ResponseBody: every return value is written to the response, usually as JSON. It is what a REST (Representational State Transfer) API uses, and it is why no view is resolved.

@Configuration: Is a @Component. Holds @Bean methods. A class of @Bean methods. By default it is proxied, so one @Bean method calling another gets the same shared bean instead of a new object. proxyBeanMethods = false turns that off.

Six rows, one per stereotype. Each has a button with the annotation, the annotation it carries, and what it adds.

@Component: The root. Found by the scan. Marks any class as a bean. The scan finds it, and the container creates and wires it. Every stereotype below carries this annotation, so all of them are found the same way.

@Service: Is a @Component. Adds no behavior. Says this class holds business logic. Spring adds nothing to it today, so swapping it for @Component changes no behavior. It documents intent, and pointcuts can target it.

@Repository: Is a @Component. Translates exceptions. Says this class accesses data. It is the one with real behavior: a database or JPA exception is translated into a DataAccessException, such as DataIntegrityViolationException, so callers do not depend on the vendor.

@Controller: Is a @Component. Handles web requests. Says this class handles web requests. Spring MVC looks for it when it maps URLs to methods. By default a returned String is a view name, not a response body.

@RestController: Is a @Controller. Adds @ResponseBody. A @Controller plus @ResponseBody: every return value is written to the response, usually as JSON. It is what a REST (Representational State Transfer) API uses, and it is why no view is resolved.

@Configuration: Is a @Component. Holds @Bean methods. A class of @Bean methods. By default it is proxied, so one @Bean method calling another gets the same shared bean instead of a new object. proxyBeanMethods = false turns that off.

Takeaway: Every stereotype is a @Component, so the scan finds them all. Only some add behavior: @Repository translates exceptions, and @RestController writes the response body.

Two beans of the same type

Predict

Two beans implement Gateway: stripe and paypal. PaymentService asks for one Gateway in a parameter named gateway. Neither bean has any marking.

What happens at startup?
View as text

Two bean boxes, stripe and paypal, above a PaymentService box. A line of code shows its constructor parameter, arrows show which bean it receives, and a mark gives the result. Two beans implement Gateway: stripe and paypal. PaymentService asks for one Gateway in a parameter named gateway. Neither bean has any marking. The learner first predicts what happens at startup.

Two candidates and no way to choose. The application does not start: NoUniqueBeanDefinitionException, expected single matching bean but found 2.

The fallback: a parameter named paypal matches that bean name. It works, but renaming a parameter now changes which bean you get.

@Primary makes stripe the default. Every plain injection point gets it, and paypal stays available for anyone who asks by name.

@Qualifier at the injection point beats @Primary: this one service gets paypal, while the rest of the application keeps the default.

Ask for List<Gateway> and you get every implementation, with no conflict. That is how you build a strategy map.

Two bean boxes, stripe and paypal, above a PaymentService box. A line of code shows its constructor parameter, arrows show which bean it receives, and a mark gives the result. Two beans implement Gateway: stripe and paypal. PaymentService asks for one Gateway in a parameter named gateway. Neither bean has any marking. The learner first predicts what happens at startup.

Two candidates and no way to choose. The application does not start: NoUniqueBeanDefinitionException, expected single matching bean but found 2.

The fallback: a parameter named paypal matches that bean name. It works, but renaming a parameter now changes which bean you get.

@Primary makes stripe the default. Every plain injection point gets it, and paypal stays available for anyone who asks by name.

@Qualifier at the injection point beats @Primary: this one service gets paypal, while the rest of the application keeps the default.

Ask for List<Gateway> and you get every implementation, with no conflict. That is how you build a strategy map.

Takeaway: With several candidates, Spring tries @Qualifier, then @Primary, then the parameter name. If nothing decides, the application refuses to start.

How Spring chooses among several candidatesWith several beans of one type, a Qualifier at the injection point wins first. Otherwise a Primary bean wins. Otherwise a parameter name that matches a bean name wins. If nothing decides, the application fails to start.Several beans of onetype1. @Qualifier at theinjection point2. A @Primary bean3. Parameter nameequals a bean nameOtherwise: startupfails
How Spring chooses among several candidatesWith several beans of one type, a Qualifier at the injection point wins first. Otherwise a Primary bean wins. Otherwise a parameter name that matches a bean name wins. If nothing decides, the application fails to start.Several beans of onetype1. @Qualifier at theinjection point2. A @Primary bean3. Parameter nameequals a bean nameOtherwise: startupfails
How Spring chooses among several candidates

In code

@Configuration
class PaymentConfig {
    @Bean @Primary
    Gateway stripe() { return new StripeGateway(); }

    @Bean
    Gateway paypal() { return new PaypalGateway(); }
}

@Service
class RefundService {
    private final Gateway gateway;

    // Beats @Primary, for this injection point only
    RefundService(@Qualifier("paypal") Gateway gateway) {
        this.gateway = gateway;
    }
}
Two gateways, one default, one explicit choice
@Configuration
class ClientConfig {
    @Bean
    RestClient paymentsClient(RestClient.Builder builder) {
        return builder.baseUrl("https://pay.example").build();
    }
}
@Bean for a class you cannot annotate
Component or BeanA class you own takes a stereotype such as Service, and the component scan finds it. A class from a library cannot be annotated, or needs logic to build, so a Bean method in a Configuration class registers it.A class you own@Service,@Component:the scan finds itA library class, oronethat needs logic tobuild@Bean method in a@Configurationclass
Component or BeanA class you own takes a stereotype such as Service, and the component scan finds it. A class from a library cannot be annotated, or needs logic to build, so a Bean method in a Configuration class registers it.A class you own@Service,@Component:the scan finds itA library class, oronethat needs logic tobuild@Bean method in a@Configurationclass
@Component or @Bean
// com/shop/ShopApplication.java
@SpringBootApplication                      // scans com.shop and every package below it
public class ShopApplication {}

// com/shared/audit/AuditLog.java
@Component                                  // outside com.shop: never found, "No qualifying bean"
public class AuditLog {}

// one fix: name both roots (a shared library should use auto-configuration instead)
@SpringBootApplication(scanBasePackages = {"com.shop", "com.shared.audit"})
Component scan starts at the package of @SpringBootApplication

Solve it

Add a second DataSource without breaking JPA (Jakarta Persistence API)

The app reads orders from one database. A reporting feature adds a second DataSource bean, and startup fails: “required a single bean, but 2 were found”. Make JPA keep the orders database and give reporting its own.

  1. Read the error. Injection by type found two DataSource candidates and no rule to choose one.
  2. Know what changed. Defining your own DataSource makes Boot’s auto-configured one back off, so now you define both.
  3. Mark the default. @Primary on the orders DataSource: JPA and anything else that asks by type gets it.
  4. Ask for the other by name. The reporting code injects @Qualifier("reportingDataSource").
  5. Check. The app starts, and a test asserts that each bean’s connection URL points at its own database.
@Configuration
class DataSources {
    @Bean @Primary
    @ConfigurationProperties("app.datasource.orders")      // keys: jdbc-url, username, password
    DataSource ordersDataSource() { return DataSourceBuilder.create().build(); }

    @Bean
    @ConfigurationProperties("app.datasource.reporting")
    DataSource reportingDataSource() { return DataSourceBuilder.create().build(); }
}

@Repository
class ReportQueries {
    private final JdbcTemplate jdbc;
    ReportQueries(@Qualifier("reportingDataSource") DataSource reporting) { this.jdbc = new JdbcTemplate(reporting); }
}
One primary DataSource, and one chosen by name

How to answer

  • @RestController is @Controller plus @ResponseBody.
  • Stereotypes let pointcuts and test slices target a layer.
  • Swapping @Service for @Component changes no behavior.
  • The default bean name is the class name with a lowercase first letter.

Common mistakes

  • Claiming @Service starts transactions or adds other behavior by itself.
  • Saying @Repository is required for Spring Data interfaces, which are detected without it.

Follow-up questions

When do you use @Bean instead of @Component?

@Component goes on a class you own, and the scan finds it. @Bean goes on a method in a @Configuration class, and you write the code that creates the object. Use @Bean for a class from a library, which you cannot annotate, or when creation needs logic or several configured instances of one type. The bean name defaults to the method name.

  • One class can have several @Bean methods with different settings.
  • Parameters of a @Bean method are injected like constructor arguments.
  • @Bean also takes initMethod, destroyMethod and scope settings.
@Configuration
class ClientConfig {
    @Bean
    RestClient paymentsClient(RestClient.Builder builder) {
        return builder.baseUrl("https://pay.example").build();
    }
}

See it in the infographic: The stereotype family

What is the difference between @Qualifier and @Primary?

Both solve "several beans of one type". @Primary goes on a bean and makes it the default wherever nothing more specific is asked. @Qualifier goes on the injection point and names the bean wanted there. @Qualifier wins when both apply. With neither, a parameter name that matches a bean name is the fallback, and otherwise startup fails.

  • @Primary decides at the provider; @Qualifier decides at the consumer.
  • Both can be avoided by injecting List<Gateway> or Map<String, Gateway>.
  • The map's keys are bean names, which suits a strategy lookup.

See it in the infographic: Two beans of the same type

Your @Service is not found, and startup fails with a missing bean. What do you check?

First the package. @SpringBootApplication scans the package of its own class and everything below it, so a class in a sibling package is never found. Move the main class up to the root package, or add @ComponentScan or @Import. Then check the stereotype is on the implementation, not the interface, and that no profile or condition excludes it.

  • The main class belongs in the root package, above everything else.
  • A stereotype on an interface does not register a bean.
  • A class in a shared library usually joins through auto-configuration, not by a wider scan.

See it in the infographic: The stereotype family

What does exception translation in @Repository give you?

It turns vendor exceptions, from Hibernate or JDBC (Java Database Connectivity), into Spring's DataAccessException hierarchy. A service can catch DataIntegrityViolationException for a duplicate key, with no dependency on the database or the ORM (object-relational mapping). The translation happens in a proxy around the repository, so it applies to calls coming from outside the bean.

  • DataAccessException is unchecked, so it does not spread through method signatures.
  • A unique key violation arrives as DataIntegrityViolationException, whichever database you use.
  • Translation depends on the proxy, like @Transactional.

See it in the infographic: The stereotype family

What is the difference between @Configuration and @Component on a class with @Bean methods?

A @Configuration class is proxied, so one @Bean method calling another returns the shared bean. In a @Component class, or with proxyBeanMethods = false, that call is a plain Java call, and you get a second object the container does not manage. Boot's own auto-configurations use proxyBeanMethods = false, and take dependencies as parameters.

  • With proxyBeanMethods = true the call returns the same instance, and with false a new one.
  • Declaring dependencies as method parameters works in both modes.
  • false avoids creating a subclass, so startup does less work.
@Configuration
class Config {
    @Bean Engine engine() { return new Engine(); }

    // The same Engine bean, because the class is proxied
    @Bean Car car() { return new Car(engine()); }
}

See it in the infographic: The stereotype family

Does a Spring Data repository interface need @Repository?

No. Spring Data finds interfaces that extend Repository, and creates an implementation at startup. Exception translation is applied to that implementation for you, so a unique key violation already arrives as DataIntegrityViolationException.

Why can a stereotype be used on a custom annotation?

Spring reads annotations on annotations. If @AuditedService is itself annotated with @Service, a class using it is found by the scan and is a bean. That is how Spring Boot builds composed annotations such as @SpringBootApplication.

What does @Controller do differently from @RestController when a method returns a String?

In @Controller, the String is a view name, which a view resolver turns into a page. In @RestController, the String is written to the response body as is. Adding @ResponseBody to a single method gives a @Controller the same behavior for that method.

Check yourself

1. Two beans implement PaymentGateway. A service asks for one PaymentGateway in a parameter named gateway. Neither bean is marked. What happens?
Show answers
  • The application fails to start.: Correct. Spring finds two candidates and nothing decides, so it throws NoUniqueBeanDefinitionException.
  • It injects the first one declared.: Incorrect. Declaration order only orders a List. It never chooses for a single injection point.
  • It injects null, and the first call fails.: Incorrect. A required dependency is never left null. The failure comes at startup.
2. stripe has @Primary. A constructor parameter has @Qualifier("paypal"). Which bean is injected there?
Show answers
  • paypal: Correct. The qualifier is the more specific request, so it beats @Primary at this injection point.
  • stripe: Incorrect. @Primary is only the default when the injection point does not ask for something specific.
  • Startup fails with a conflict.: Incorrect. There is no conflict. The two annotations have a defined order.
3. Which stereotype adds behavior beyond being found by the scan and documenting intent?
Show answers
  • @Repository: Correct. It translates persistence exceptions into Spring's DataAccessException hierarchy.
  • @Service: Incorrect. It adds nothing today. It is a @Component with a more specific name.
  • @Component: Incorrect. It is the base annotation. It only makes the class a bean.