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

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. The others, @Service, @Repository, @Controller and @Configuration, are themselves annotated with @Component. Spring follows these meta-annotations, so a class marked @Service counts as a @Component too. They are called stereotypes because they name the role a class plays in a layered application.

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 methods.

Spring's stereotype annotations
AnnotationSinceRoleWhat it adds beyond @Component
@Component2.5Any beanNothing; it is the base
@Service2.5Business logicNothing in the framework; it documents the role
@Repository2.0Data accessException translation to DataAccessException, when enabled
@Controller2.5Spring MVC controllerDetected as a handler by Spring MVC
@RestController4.0REST controller@Controller plus @ResponseBody on every method
@Configuration3.0Bean definitions@Bean method processing, and a CGLIB subclass in full mode

The examples are complete programs on Spring Framework 7.0 without Spring Boot. The first also uses spring-web, for @RestController; the last uses the jakarta.inject and jakarta.annotation APIs.

The stereotypes are meta-annotated with @Component

Spring's MergedAnnotations API reads annotations the way the container does, following meta-annotations. This program asks each class for its @Component and prints the chain that leads to it:

Java
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");
        }
    }
}
Output
AService:         @Service -> @Component
ARepository:      @Repository -> @Component
AController:      @Controller -> @Component
ARestController:  @RestController -> @Controller -> @Component
AConfiguration:   @Configuration -> @Component
NotABean:         not a component
  • @Service, @Repository, @Controller and @Configuration each reach @Component in one step. To the scanner, all four mean "create a bean from this class".
  • @RestController takes two steps: it is annotated with @Controller, which is annotated with @Component. Meta-annotations can nest to any depth.
  • NotABean has no @Component anywhere in its annotations, so scanning would ignore it.

Because the container treats them alike, choosing @Service over @Component changes nothing at run time. It still matters to readers, and to tools: aspects, architecture tests and scan filters can select classes by stereotype, as a later section shows.

Component scanning and bean names

@ComponentScan without arguments scans the package of the class it is on, and every package below it. This program's package, shop.scan, holds a mix of classes chosen to show the naming rules and what scanning skips:

Java
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
}
Output
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: OrderService became orderService, and OrderRepository became orderRepository.
  • URLShortener kept its name unchanged. Spring follows the JavaBeans rule of Introspector.decapitalize: when the first two letters are both upper case, the name is left as it is.
  • @Component("payments") set an explicit name, so the bean is payments, not paymentClient. Every stereotype takes the name as its value.
  • The static nested class XmlExporter.Settings was found too, and named xmlExporter.Settings, after its enclosing class.
  • PlainHelper has no annotation and AbstractHandler is abstract, so neither appears. The configuration class itself, scanBasics, is a bean because @Configuration is a component.
  • OrderService received OrderRepository and PaymentClient through its constructor. Scanned classes are injected exactly like beans from @Bean methods.

Scan a specific package with @ComponentScan("com.example.orders"), or with basePackageClasses = OrderService.class, which survives renaming a package. Spring Boot's @SpringBootApplication includes @ComponentScan, which is why the main class belongs in the root package of the application: classes in sibling packages are not found. Two classes with the same simple name in different scanned packages produce the same bean name, and startup fails with ConflictingBeanDefinitionException; give one of them an explicit name.

@Repository and exception translation

@Repository is the stereotype with a real extra. With a PersistenceExceptionTranslationPostProcessor in the context, Spring wraps every @Repository bean in a proxy that converts exceptions from the persistence technology into Spring's DataAccessException hierarchy. The conversion itself is done by PersistenceExceptionTranslator beans. JPA and Hibernate setups register one; here a small translator stands in for a driver that reports duplicate keys with error code 1062:

Java
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());
            }
        }
    }
}
Output
@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 @Repository bean is a proxy, UserRepository$$SpringCGLIB$$0. Its method threw StoreException, and the caller received DuplicateKeyException, which is a DataAccessException. The original exception is kept as the cause.
  • The @Component bean has the same code, but it is not proxied, and the caller received the raw StoreException.

The point of the translation is that a service can catch DuplicateKeyException or DataAccessException whether the repository uses JDBC, JPA or another store. Spring Boot registers the post-processor automatically when a persistence starter, such as the JDBC or JPA one, is on the classpath. JdbcTemplate translates SQLException by itself, so a JDBC repository gets Spring's exceptions with or without the stereotype. Spring Data repository interfaces are translated too, without any annotation.

Custom stereotypes and scan filters

Any annotation that is meta-annotated with @Component works as a stereotype. With @AliasFor, its value can set the bean name, just as @Service("name") does. @ComponentScan filters then decide what is registered. This package declares a @UseCase stereotype and scans itself with two configurations:

Java
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);
    }
}
Output
DefaultFiltersConfig: checkout, legacyReportService, refundUseCase, taxRules
UseCasesOnlyConfig: checkout, refundUseCase
  • With the default filters, both @UseCase classes were found, because @UseCase carries @Component. @UseCase("checkout") named its bean checkout through the alias; RefundUseCase got the default name refundUseCase.
  • TaxRules has no annotation, yet it became the bean taxRules: the regular-expression include filter added it. Include filters add to the default @Component filter rather than replacing it.
  • ExperimentalPricing is a @Service but is missing, because the exclude filter matched its name. Exclude filters win over include filters.
  • With useDefaultFilters = false and an include filter on @UseCase, only the two use cases were registered. LegacyReportService, a plain @Service, was not.

Filter types include ANNOTATION (the default), ASSIGNABLE_TYPE, REGEX, ASPECTJ and CUSTOM, which takes your own TypeFilter. Composed annotations go further than stereotypes: an annotation can combine @Service with @Transactional, or @Component with @Scope, so that one annotation carries a whole set of settings.

@Autowired, @Inject and @Resource

Spring also supports two standard sets of annotations: JSR-330 (@Inject, @Named) from jakarta.inject, and JSR-250 (@Resource) from jakarta.annotation. They resolve dependencies in slightly different ways. This program injects one of two Storage beans four times:

Java
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)));
        }
    }
}
Output
@Autowired + @Qualifier : local disk
@Inject + @Named        : cloud bucket
@Resource (field name)  : cloud bucket
@Resource(name = ...)   : local disk
@Named class registered as: cloudStorage
  • @Autowired with @Qualifier("localStorage") picked the local storage. @Autowired matches by type first and uses the qualifier to choose between candidates.
  • @Inject with @Named("cloudStorage") behaved the same way and picked the cloud storage. @Inject is the standard equivalent of @Autowired, without a required attribute.
  • @Resource on the field cloudStorage found the bean whose name equals the field name. @Resource matches by name first and falls back to type only when no bean has that name.
  • @Named("cloudStorage") on the class registered it as a bean named cloudStorage. Used on a class, @Named is the standard equivalent of @Component.

In Spring Framework 7, only the jakarta packages are recognized; the old javax.inject and javax.annotation versions are ignored, as the bean lifecycle page shows for @PostConstruct. Most Spring code uses @Autowired, or no annotation at all with a single constructor. The standard annotations suit code that should also run under another dependency injection container.

Other annotations you will meet on beans

Annotations that change how a bean is registered or injected
AnnotationEffectCovered on
@Scope, @RequestScope, @SessionScopeInstances per context, request or sessionBean scopes
@LazyCreate on first use instead of at startupJava configuration
@Primary, @Fallback, @QualifierChoose between beans of the same typeDependency injection
@OrderOrder in injected listsDependency injection
@Profile, @ConditionalRegister only in some environmentsJava configuration
@ValueInject a property or expressionJava configuration
@PostConstruct, @PreDestroyRun code after creation and before destructionBean lifecycle
@DependsOnCreate another bean firstJava configuration

All of these work the same on a scanned class and on a @Bean method.

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 com 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.
  • Annotating the interface: @Service on an interface does nothing, because interfaces are skipped. Annotate the implementation.
  • Both a stereotype and a @Bean method: a class annotated @Component and also returned from a @Bean method gives two beans of the same type, and injection by type then fails as ambiguous. Use one or the other.
  • Expecting @Service to do something: @Service adds no transactions, security or proxies by itself. Those come from @Transactional and similar annotations.

Choosing an annotation

Which stereotype for which class
ClassAnnotation
Business logic, use cases@Service
Data access written by hand@Repository, for exception translation
Spring Data repository interfaceNone; Spring Data creates the bean
Web controller returning views@Controller
REST controller returning data@RestController
Class with @Bean methods@Configuration
Anything else: clients, mappers, helpers@Component
A role specific to your architectureYour own stereotype, meta-annotated with @Component
A class from a libraryNo stereotype possible: a @Bean method

Pick the stereotype that names the role, inject through the constructor, and keep scanning limited to your own packages. The Java configuration page covers @Bean methods for the classes you cannot annotate, and inversion of control explains the container that reads all of these annotations.