Component scanning

Key idea
With `@ComponentScan`, Spring walks the packages you tell it and registers as a bean every class annotated with `@Component` (or a stereotype). Then it injects by type and, when there are several candidates, breaks the tie with `@Primary`, `@Qualifier` or the parameter name.
In the box
Every payment method in the box meant adding a @Bean by hand. Annotate the classes, let Spring find them, and learn to choose among several candidates with @Primary, @Qualifier, lists, maps and optional dependencies.
ManualPaymentConfigcardPaymentcashPaymentbizum

ManualPaymentConfig, highlighted in red, creates the three payment beans with @Bean: cardPayment, cashPayment and bizum.

View of the context: BoxScanConfig, highlighted, finds cardPayment and leaves out LegacyPayment, in red. Below are CheckoutService, MembershipRepository, the PaymentMethod interface and the three payment methods.

MembershipRepository and CheckoutService are highlighted. A @Repository packet travels from BoxScanConfig to the repository.

Receipts, in red, asks the interface for a PaymentMethod; cashPayment and bizum, also highlighted, are two candidates for the same slot.

cardPayment and CheckoutService are highlighted. A @Primary packet reaches the service from PaymentMethod.

CheckoutService and PaymentMethod are highlighted. A List · Map packet travels from the interface to the service: it receives every payment method.

The LoyaltyProgram? interface appears, highlighted in amber; an empty packet travels towards CheckoutService because no bean implements it.

The athlete sends method=bizum to CheckoutService, highlighted, and the charge() call goes back through the PaymentMethod interface to the chosen payment method.

Final view: BoxScanConfig, CheckoutService, MembershipRepository, the PaymentMethod interface and its three implementations inside the context.

Step 1 of 9

One @Bean per class

The box takes card, cash and Bizum. With what you know, each payment method is a @Bean method in a configuration class, ManualPaymentConfig.

It works, but each new payment method means touching two places: writing the class and remembering to register it. And the configuration class keeps growing with methods that only call new.

Step 2 of 9

@Component + @ComponentScan

Turn it around: annotate each class with @Component and ask Spring to look for them with @ComponentScan.

  • basePackages says where to look. If you leave it out, the annotated class's package and all its subpackages are scanned.
  • excludeFilters / includeFilters refine the search by annotation, type, regular expression, AspectJ or a custom filter. Here LegacyPayment has @Component but a filter leaves it out.
  • The bean name is the class name with a lower-case first letter (cardPayment), unless you give one: @Component("bizum").

Step 3 of 9

Stereotypes: @Service, @Repository, @Controller

@Component has "surnames" that tell the layer:

  • @Service for business logic (CheckoutService).
  • @Repository for data access (MembershipRepository). It also enables exception translation: driver or JPA exceptions are turned into Spring's DataAccessException hierarchy.
  • @Controller / @RestController for the web.
  • @Configuration is a @Component too, which is why scanning finds configuration classes.

Step 4 of 9

Two candidates, no winner

Receipts asks for one PaymentMethod in its constructor, but the context has two: cash and Bizum. Spring resolves dependencies by type, and here type isn't enough.

The context doesn't start: UnsatisfiedDependencyException, with root cause NoUniqueBeanDefinitionException.

Before giving up, Spring tries in this order:

  1. Is there a single candidate of that type? Done.
  2. Is one of them @Primary?
  3. Does the injection point carry @Qualifier?
  4. Is there a bean with the same name as the parameter or field?

Step 5 of 9

@Primary: the default candidate

CardPayment carries @Primary. From then on, whoever asks for one PaymentMethod with no further detail gets the card. CheckoutService uses it as the default payment method.

@Primary also works on a @Bean method. There can only be one @Primary per type; with two, you're back to ambiguity.

Step 6 of 9

@Qualifier, lists and maps

Look at CheckoutService's constructor, which asks for several things of the same type:

  • PaymentMethod defaultMethod: the @Primary one, the card.
  • @Qualifier("cashPayment") PaymentMethod cash: a specific one, by name. @Qualifier beats @Primary.
  • List<PaymentMethod> all: all the beans of that type (ordered with @Order or Ordered if they have it).
  • Map<String, PaymentMethod> byName: all of them, keyed by bean name. So pay("Leo", "bizum", …) chooses at runtime.

Since the class has a single constructor, @Autowired isn't needed. With several constructors, you mark the one Spring should use.

Step 7 of 9

Optional dependencies

LoyaltyProgram is an interface nobody implements yet. If CheckoutService asked for it as a plain parameter, startup would fail with NoSuchBeanDefinitionException.

For things that may be missing you have several options:

  • Optional<LoyaltyProgram>: arrives empty when there's no bean (what the example uses).
  • @Autowired(required = false) on a setter or field: it isn't called, or stays null.
  • ObjectProvider<LoyaltyProgram>: you resolve it when needed, with getIfAvailable().
  • @Nullable on the parameter.

Step 8 of 9

A payment, end to end

The athlete pays €15 with Bizum: POST /api/checkout?athlete=Leo&method=bizum&amount=15.

CheckoutService checks in the repository that Leo is a member, looks up "bizum" in the map and calls charge(). Without method, it would use the default, the @Primary card.

The test checks all of it with a context that loads only BoxScanConfig and CheckoutService: the @Primary, the @Qualifier, the list of three, the map by name and the empty Optional.

Step 9 of 9

Recap

  • @Component (or @Service, @Repository, @Controller, @Configuration) + @ComponentScan = beans without writing @Bean.
  • Scanning starts at the annotated class's package unless told otherwise, and is refined with filters.
  • Resolution: type → @Primary → @Qualifier → parameter name. If nothing breaks the tie, startup fails.
  • Many: List<T> and Map<String, T>. None: Optional, required = false, ObjectProvider.

Cheatsheet →

Code

ManualPaymentConfig.java

/** Before: one @Bean method per class. Every new payment method means editing this file. */
@Configuration
public class ManualPaymentConfig {
    @Bean
    PaymentMethod cardPayment() {
        return new CardPayment();
    }

    @Bean
    PaymentMethod cashPayment() {
        return new CashPayment();
    }

    @Bean
    PaymentMethod bizum() {
        return new BizumPayment();
    }
    // … and one more for each new class
}

BoxScanConfig.java

@Configuration
@ComponentScan(
    basePackages = {"com.spring2learn.box.scan.payments", "com.spring2learn.box.scan.members"},
    excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*Legacy.*"))
public class BoxScanConfig {
}

MembershipRepository.java

@Repository // a @Component for the data layer: also enables exception translation
public class MembershipRepository {
    private final Set<String> active = Set.of("Ana", "Leo", "Marta");

    public boolean isActive(String athlete) {
        return active.contains(athlete);
    }
}

AmbiguityTest.java

@Component
static class Receipts {
    Receipts(PaymentMethod method) { }        // which one? cash or bizum?
}

@Test
void twoCandidatesAndNoPrimaryFailAtStartup() {
    assertThatThrownBy(() -> new AnnotationConfigApplicationContext(
            CashPayment.class, BizumPayment.class, Receipts.class))
        .isInstanceOf(UnsatisfiedDependencyException.class)
        .hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class);
}

CardPayment.java

@Component   // found by the scan; bean name "cardPayment" (class name, first letter lower case)
@Primary     // the default when someone asks for one PaymentMethod
public class CardPayment implements PaymentMethod {
    @Override
    public String charge(String athlete, BigDecimal amount) {
        return "card:" + athlete + ":" + amount;
    }
}

CheckoutService.java

// One constructor: no @Autowired needed. Each parameter is resolved by type…
public CheckoutService(MembershipRepository members,
                       PaymentMethod defaultMethod,                     // two+ candidates → @Primary wins
                       @Qualifier("cashPayment") PaymentMethod cash,    // …or narrowed by name
                       List<PaymentMethod> all,                         // every PaymentMethod bean
                       Map<String, PaymentMethod> byName,               // bean name → bean
                       Optional<LoyaltyProgram> loyalty) {              // may be missing
    this.members = members;
    this.defaultMethod = defaultMethod;
    this.cash = cash;
    this.all = all;
    this.byName = byName;
    this.loyalty = loyalty;
}

CheckoutService.java

public String pay(String athlete, String method, BigDecimal amount) {
    if (!members.isActive(athlete)) {
        throw new IllegalArgumentException("not a member: " + athlete);
    }
    PaymentMethod chosen = method == null ? defaultMethod : byName.get(method);
    if (chosen == null) {
        throw new IllegalArgumentException("unknown method: " + method + ", try " + byName.keySet());
    }
    return chosen.charge(athlete, amount);
}

public int loyaltyPoints(String athlete) {
    return loyalty.map(program -> program.pointsFor(athlete)).orElse(0); // no bean: no points
}

ScanTest.java

@Test
void primaryQualifierListAndMapResolveTheCandidates() {
    try (var ctx = new AnnotationConfigApplicationContext(BoxScanConfig.class, CheckoutService.class)) {
        CheckoutService checkout = ctx.getBean(CheckoutService.class);

        assertThat(checkout.pay("Ana", null, BigDecimal.TEN)).startsWith("card:");   // @Primary
        assertThat(checkout.cashDesk()).isInstanceOf(CashPayment.class);            // @Qualifier
        assertThat(checkout.methods()).hasSize(3);                                  // List<PaymentMethod>
        assertThat(checkout.pay("Ana", "bizum", BigDecimal.TEN)).startsWith("bizum:"); // Map by name
        assertThat(checkout.loyaltyPoints("Ana")).isZero();                          // Optional.empty()
        assertThat(ctx.getBean(PaymentMethod.class)).isInstanceOf(CardPayment.class);
    }
}

CheckoutService.java

// One constructor: no @Autowired needed. Each parameter is resolved by type…
public CheckoutService(MembershipRepository members,
                       PaymentMethod defaultMethod,                     // two+ candidates → @Primary wins
                       @Qualifier("cashPayment") PaymentMethod cash,    // …or narrowed by name
                       List<PaymentMethod> all,                         // every PaymentMethod bean
                       Map<String, PaymentMethod> byName,               // bean name → bean
                       Optional<LoyaltyProgram> loyalty) {              // may be missing
    this.members = members;
    this.defaultMethod = defaultMethod;
    this.cash = cash;
    this.all = all;
    this.byName = byName;
    this.loyalty = loyalty;
}

Quiz

1. AppConfig lives in com.box and carries @ComponentScan with no attributes. Which packages are scanned?

2. CashPayment and BizumPayment implement PaymentMethod, neither is @Primary, and a constructor asks for `PaymentMethod method`. What happens?

3. CardPayment is @Primary. A parameter is annotated with @Qualifier("cashPayment"). What does it get?

4. What does a `Map<String, PaymentMethod>` injected by Spring contain?

5. Which of these annotations is NOT meta-annotated with @Component?

6. You want to inject a LoyaltyProgram that may not exist. Which option does NOT work?

Cheatsheet → · Mock exam →

Run it