Cheatsheet

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.

Diagram (UML)

ApplicationContextBoxScanConfigCheckoutServiceMembershipRepository«i»PaymentMethodcardPaymentcashPaymentbizum

Key pieces

  • @Component and its stereotypes: @Service, @Repository, @Controller/@RestController, @Configuration
  • @ComponentScan(basePackages, basePackageClasses, includeFilters, excludeFilters)
  • @Autowired: on a constructor (optional with a single one), setter or field; required = false
  • @Primary: the default candidate; @Qualifier("name"): a specific candidate
  • List<T>, Map<String, T>, Optional<T>, ObjectProvider<T>: inject many or none

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;
}

Remember for the exam

  • Without basePackages, the package of the annotated class and all its subpackages are scanned
  • The default name is the class name with a lower-case first letter: CardPayment → cardPayment
  • Resolution order: by type → @Primary → @Qualifier → parameter or field name
  • Map<String, T> uses each bean's name as the key
  • @Repository adds translation of persistence exceptions into DataAccessException
  • @SpringBootApplication includes @ComponentScan on the main class's package

Exam traps

  • Two candidates with no @Primary or @Qualifier break startup: UnsatisfiedDependencyException caused by NoUniqueBeanDefinitionException
  • A class outside the scanned packages isn't a bean even with @Component
  • @Qualifier beats @Primary: if you ask for a specific one, you get that one
  • A missing mandatory dependency throws NoSuchBeanDefinitionException at startup; use Optional, required = false or ObjectProvider if it's optional

← Component scanning · Run it