Spring stereotype annotations and component scanning
@Component, @Service, @Repository and @Controller all register a class as a bean, and to the container they are almost the same annotation. This page shows why, how component scanning finds the classes and names the beans, the one real extra that @Repository brings, how to write your own stereotype and filter what is scanned, and how the standard @Inject and @Resource annotations compare with @Autowired.
Contents
What stereotype annotations are The stereotypes are meta-annotated with @Component Component scanning and bean names @Repository and exception translation Custom stereotypes and scan filters @Autowired, @Inject and @Resource Other annotations you will meet on beans Pitfalls with scanning Choosing an annotation
What stereotype annotations are
Spring needs to know which classes it should create as beans. Instead of listing them in a configuration file, you can mark each class with an annotation and let Spring find them. That search is component scanning: Spring walks the class files under a package, reads each one's annotations, and registers a bean definition for every class marked as a component.
The base marker is @Component@Service@Repository@Controller@Configuration@Component@Service@Component
Scanning reads class files with a bytecode reader rather than loading every class, so classes that turn out not to be components are never initialized. A candidate must be a concrete, top-level or static nested class. Interfaces, abstract classes and non-static inner classes are skipped, unless a class has @Lookup
| Annotation | Since | Role | What it adds beyond @Component |
|---|---|---|---|
@Component | 2.5 | Any bean | Nothing; it is the base |
@Service | 2.5 | Business logic | Nothing in the framework; it documents the role |
@Repository | 2.0 | Data access | Exception translation to DataAccessException |
@Controller | 2.5 | Spring MVC controller | Detected as a handler by Spring MVC |
@RestController | 4.0 | REST controller | @Controller@ResponseBody |
@Configuration | 3.0 | Bean definitions | @Bean |
The examples are complete programs on Spring Framework 7.0 without Spring Boot. The first also uses spring-web@RestControllerjakarta.injectjakarta.annotation
The stereotypes are meta-annotated with @Component
Spring's MergedAnnotations@Component
import java.lang.annotation.Annotation;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
public class StereotypeTree {
@Service
static class AService {
}
@Repository
static class ARepository {
}
@Controller
static class AController {
}
@RestController
static class ARestController {
}
@Configuration
static class AConfiguration {
}
static class NotABean {
}
public static void main(String[] args) {
List<Class<?>> classes = List.of(AService.class, ARepository.class, AController.class,
ARestController.class, AConfiguration.class, NotABean.class);
for (Class<?> type : classes) {
MergedAnnotations annotations = MergedAnnotations.from(type);
MergedAnnotation<Component> component = annotations.get(Component.class);
StringBuilder path = new StringBuilder();
if (component.isPresent()) {
for (Class<? extends Annotation> step : component.getMetaTypes()) {
path.append(path.isEmpty() ? "" : " -> ").append("@")
.append(step.getSimpleName());
}
}
System.out.printf("%-17s %s%n", type.getSimpleName() + ":",
component.isPresent() ? path : "not a component");
}
}
}
AService: @Service -> @Component
ARepository: @Repository -> @Component
AController: @Controller -> @Component
ARestController: @RestController -> @Controller -> @Component
AConfiguration: @Configuration -> @Component
NotABean: not a component
,@Service ,@Repository and@Controller each reach@Configuration in one step. To the scanner, all four mean "create a bean from this class".@Component takes two steps: it is annotated with@RestController , which is annotated with@Controller . Meta-annotations can nest to any depth.@Component has noNotABean anywhere in its annotations, so scanning would ignore it.@Component
Because the container treats them alike, choosing @Service@Component
Component scanning and bean names
@ComponentScanshop.scan
package shop.scan;
import java.util.Arrays;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Configuration
@ComponentScan // no package given: scans the package of this class, shop.scan
public class ScanBasics {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(ScanBasics.class)) {
String[] names = context.getBeanDefinitionNames();
Arrays.sort(names);
for (String name : names) {
if (!name.startsWith("org.springframework")) {
System.out.printf("%-22s -> %s%n", name,
context.getType(name).getSimpleName());
}
}
System.out.println("OrderService got: "
+ context.getBean(OrderService.class).describe());
}
}
}
@Repository
class OrderRepository {
}
@Service
class OrderService {
private final OrderRepository repository;
private final PaymentClient payments;
OrderService(OrderRepository repository, PaymentClient payments) {
this.repository = repository;
this.payments = payments;
}
String describe() {
return repository.getClass().getSimpleName() + " and "
+ payments.getClass().getSimpleName();
}
}
@Component("payments")
class PaymentClient {
}
@Component
class URLShortener {
}
@Component
class XmlExporter {
@Component
static class Settings {
}
}
class PlainHelper { // no annotation: not a bean
}
@Component
abstract class AbstractHandler { // abstract: skipped by scanning
}
URLShortener -> URLShortener
orderRepository -> OrderRepository
orderService -> OrderService
payments -> PaymentClient
scanBasics -> ScanBasics
xmlExporter -> XmlExporter
xmlExporter.Settings -> Settings
OrderService got: OrderRepository and PaymentClient
- The default bean name is the simple class name with its first letter lowercased:
becameOrderService , andorderService becameOrderRepository .orderRepository kept its name unchanged. Spring follows the JavaBeans rule ofURLShortener : when the first two letters are both upper case, the name is left as it is.Introspector.decapitalize set an explicit name, so the bean is@Component("payments") , notpayments . Every stereotype takes the name as itspaymentClient .value- The static nested class
was found too, and namedXmlExporter.Settings , after its enclosing class.xmlExporter.Settings has no annotation andPlainHelper is abstract, so neither appears. The configuration class itself,AbstractHandler , is a bean becausescanBasics is a component.@Configuration receivedOrderService andOrderRepository through its constructor. Scanned classes are injected exactly like beans fromPaymentClient methods.@Bean
Scan a specific package with @ComponentScan("com.example.orders")basePackageClasses = OrderService.class@SpringBootApplication@ComponentScanConflictingBeanDefinitionException
@Repository and exception translation
@RepositoryPersistenceExceptionTranslationPostProcessor@RepositoryDataAccessExceptionPersistenceExceptionTranslator
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
public class RepositoryTranslation {
// stands in for an exception type from a driver or persistence library
static class StoreException extends RuntimeException {
final int code;
StoreException(int code, String message) {
super(message);
this.code = code;
}
}
static class StoreExceptionTranslator implements PersistenceExceptionTranslator {
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException e) {
if (e instanceof StoreException store && store.code == 1062) {
return new DuplicateKeyException("duplicate key: " + store.getMessage(), store);
}
return null; // not ours: leave it alone
}
}
@Repository
public static class UserRepository {
public void save(String email) {
throw new StoreException(1062, email);
}
}
@Component
public static class UserStore { // same code, but only @Component
public void save(String email) {
throw new StoreException(1062, email);
}
}
@Configuration
static class Config {
@Bean
static PersistenceExceptionTranslationPostProcessor translation() {
return new PersistenceExceptionTranslationPostProcessor();
}
@Bean
StoreExceptionTranslator storeExceptionTranslator() {
return new StoreExceptionTranslator();
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(
Config.class, UserRepository.class, UserStore.class)) {
UserRepository repository = context.getBean(UserRepository.class);
System.out.println("@Repository bean class: " + repository.getClass().getSimpleName());
try {
repository.save("ana@example.com");
} catch (RuntimeException e) {
System.out.println(" caller sees " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
System.out.println(" is a DataAccessException: "
+ (e instanceof DataAccessException));
}
UserStore store = context.getBean(UserStore.class);
System.out.println("@Component bean class : " + store.getClass().getSimpleName());
try {
store.save("ana@example.com");
} catch (RuntimeException e) {
System.out.println(" caller sees " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
}
}
}
@Repository bean class: RepositoryTranslation$UserRepository$$SpringCGLIB$$0
caller sees DuplicateKeyException: duplicate key: ana@example.com
is a DataAccessException: true
@Component bean class : UserStore
caller sees StoreException: ana@example.com
- The
bean is a proxy,@Repository . Its method threwUserRepository$$SpringCGLIB$$0 , and the caller receivedStoreException , which is aDuplicateKeyException . The original exception is kept as the cause.DataAccessException - The
bean has the same code, but it is not proxied, and the caller received the raw@Component .StoreException
The point of the translation is that a service can catch DuplicateKeyExceptionDataAccessExceptionJdbcTemplateSQLException
Custom stereotypes and scan filters
Any annotation that is meta-annotated with @Component@AliasForvalue@Service("name")@ComponentScan@UseCase
package shop.filters;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Component
@interface UseCase {
@AliasFor(annotation = Component.class)
String value() default "";
}
@UseCase("checkout")
class CheckoutUseCase {
}
@UseCase
class RefundUseCase {
}
@Service
class LegacyReportService {
}
class TaxRules { // no annotation at all
}
@Service
class ExperimentalPricing {
}
@Configuration
@ComponentScan(
includeFilters = @ComponentScan.Filter(type = FilterType.REGEX,
pattern = "shop\\.filters\\.Tax.*"),
excludeFilters = {
@ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*Experimental.*"),
// the other configuration class in this package
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
classes = UseCasesOnlyConfig.class)})
class DefaultFiltersConfig {
}
@Configuration
@ComponentScan(useDefaultFilters = false,
includeFilters = @ComponentScan.Filter(UseCase.class))
class UseCasesOnlyConfig {
}
public class ScanFilters {
static void show(Class<?> config) {
try (var context = new AnnotationConfigApplicationContext(config)) {
String[] names = Arrays.stream(context.getBeanDefinitionNames())
.filter(name -> !name.startsWith("org.springframework"))
.filter(name -> !name.endsWith("Config"))
.sorted().toArray(String[]::new);
System.out.println(config.getSimpleName() + ": " + String.join(", ", names));
}
}
public static void main(String[] args) {
show(DefaultFiltersConfig.class);
show(UseCasesOnlyConfig.class);
}
}
DefaultFiltersConfig: checkout, legacyReportService, refundUseCase, taxRules
UseCasesOnlyConfig: checkout, refundUseCase
- With the default filters, both
classes were found, because@UseCase carries@UseCase .@Component named its bean@UseCase("checkout") through the alias;checkout got the default nameRefundUseCase .refundUseCase has no annotation, yet it became the beanTaxRules : the regular-expression include filter added it. Include filters add to the defaulttaxRules filter rather than replacing it.@Component is aExperimentalPricing but is missing, because the exclude filter matched its name. Exclude filters win over include filters.@Service- With
and an include filter onuseDefaultFilters = false , only the two use cases were registered.@UseCase , a plainLegacyReportService , was not.@Service
Filter types include ANNOTATIONASSIGNABLE_TYPEREGEXASPECTJCUSTOMTypeFilter@Service@Transactional@Component@Scope
@Autowired, @Inject and @Resource
Spring also supports two standard sets of annotations: JSR-330 (@Inject@Namedjakarta.inject@Resourcejakarta.annotationStorage
package shop.standard;
import jakarta.annotation.Resource;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
interface Storage {
String where();
}
@Component("localStorage")
class LocalStorage implements Storage {
@Override
public String where() {
return "local disk";
}
}
@Named("cloudStorage") // JSR-330: registered like @Component
class CloudStorage implements Storage {
@Override
public String where() {
return "cloud bucket";
}
}
@Component
class Uploader {
@Autowired
@Qualifier("localStorage")
Storage byAutowired;
@Inject
@Named("cloudStorage")
Storage byInject;
@Resource
Storage cloudStorage; // @Resource matches the field name first
@Resource(name = "localStorage")
Storage byResourceName;
}
@Configuration
@ComponentScan
public class StandardAnnotations {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(StandardAnnotations.class)) {
Uploader uploader = context.getBean(Uploader.class);
System.out.println("@Autowired + @Qualifier : " + uploader.byAutowired.where());
System.out.println("@Inject + @Named : " + uploader.byInject.where());
System.out.println("@Resource (field name) : " + uploader.cloudStorage.where());
System.out.println("@Resource(name = ...) : " + uploader.byResourceName.where());
System.out.println("@Named class registered as: "
+ String.join(", ", context.getBeanNamesForType(CloudStorage.class)));
}
}
}
@Autowired + @Qualifier : local disk
@Inject + @Named : cloud bucket
@Resource (field name) : cloud bucket
@Resource(name = ...) : local disk
@Named class registered as: cloudStorage
with@Autowired picked the local storage.@Qualifier("localStorage") matches by type first and uses the qualifier to choose between candidates.@Autowired with@Inject behaved the same way and picked the cloud storage.@Named("cloudStorage") is the standard equivalent of@Inject , without a@Autowired attribute.required on the field@Resource found the bean whose name equals the field name.cloudStorage matches by name first and falls back to type only when no bean has that name.@Resource on the class registered it as a bean named@Named("cloudStorage") . Used on a class,cloudStorage is the standard equivalent of@Named .@Component
In Spring Framework 7, only the jakartajavax.injectjavax.annotation@PostConstruct@Autowired
Other annotations you will meet on beans
| Annotation | Effect | Covered on |
|---|---|---|
@Scope@RequestScope@SessionScope | Instances per context, request or session | |
@Lazy | Create on first use instead of at startup | |
@Primary@Fallback@Qualifier | Choose between beans of the same type | |
@Order | Order in injected lists | |
@Profile@Conditional | Register only in some environments | |
@Value | Inject a property or expression | |
@PostConstruct@PreDestroy | Run code after creation and before destruction | |
@DependsOn | Create another bean first |
All of these work the same on a scanned class and on a @Bean
Pitfalls with scanning
- Classes outside the scanned packages: a component in a package that is not under the scan root is silently not registered, and the first sign is a missing bean at injection. In Spring Boot, keep the main class in the root package.
- Scanning too much: a scan root such as
walks every library under it and may register components you did not mean to, such as test configuration on the classpath. Scan the application's own root package only.com - Annotating the interface:
on an interface does nothing, because interfaces are skipped. Annotate the implementation.@Service - Both a stereotype and a @Bean method: a class annotated
and also returned from a@Component method gives two beans of the same type, and injection by type then fails as ambiguous. Use one or the other.@Bean - Expecting @Service to do something:
adds no transactions, security or proxies by itself. Those come from@Service and similar annotations.@Transactional
Choosing an annotation
| Class | Annotation |
|---|---|
| Business logic, use cases | @Service |
| Data access written by hand | @Repository |
| Spring Data repository interface | None; Spring Data creates the bean |
| Web controller returning views | @Controller |
| REST controller returning data | @RestController |
Class with @Bean | @Configuration |
| Anything else: clients, mappers, helpers | @Component |
| A role specific to your architecture | Your own stereotype, meta-annotated with @Component |
| A class from a library | No stereotype possible: a @Bean |
Pick the stereotype that names the role, inject through the constructor, and keep scanning limited to your own packages. The @Bean