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)
flowchart TB
scan["«@ComponentScan»<br/>basePackages + excludeFilters"]
subgraph found["Beans found by the scan"]
card["cardPayment<br/>«@Component @Primary»"]
cash["cashPayment<br/>«@Component»"]
bizum["bizum<br/>«@Component('bizum')»"]
repo["membershipRepository<br/>«@Repository»"]
end
legacy["LegacyPayment<br/>«excluded by filter»"]
scan --> found
scan -. "REGEX .*Legacy.*" .-> legacy
inj{"Inject PaymentMethod"}
inj -- "1 candidate" --> ok["that bean"]
inj -- "several, one @Primary" --> card
inj -- "@Qualifier('cashPayment')" --> cash
inj -- "parameter named bizum" --> bizum
inj -- "several, no tie-breaker" --> err["NoUniqueBeanDefinitionException"]Key pieces
@Componentand 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 candidateList<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@Repositoryadds translation of persistence exceptions intoDataAccessException@SpringBootApplicationincludes@ComponentScanon the main class's package
Exam traps
- Two candidates with no
@Primaryor@Qualifierbreak startup:UnsatisfiedDependencyExceptioncaused byNoUniqueBeanDefinitionException - A class outside the scanned packages isn't a bean even with
@Component @Qualifierbeats@Primary: if you ask for a specific one, you get that one- A missing mandatory dependency throws
NoSuchBeanDefinitionExceptionat startup; useOptional,required = falseorObjectProviderif it's optional