Definition
- @ComponentScan is an annotation that defines the base packages Spring should scan to discover classes annotated with stereotype annotations (@Component, @Service, @Repository, @Controller).
- Base package is the root package that Spring scans recursively; all sub-packages are included automatically.
- @SpringBootApplication is a composed annotation that includes @ComponentScan with no explicit base package, which means it scans the package where the main class lives and everything below it.
- BeanDefinition is the metadata object Spring creates for each discovered class, recording its type, scope, constructor arguments, and lifecycle callbacks.
- Filters are rules you can add to @ComponentScan to include or exclude specific classes by annotation, type, or regex pattern.
Think of National Bank of India doing a staff audit across all branches. The HR director (Spring container) sends a team to scan every floor of every building (packages) in the headquarters campus (base package). They look for employees wearing specific ID badges: blue for tellers (@Service), green for vault officers (@Repository), red for customer-facing staff (@Controller). Anyone without a recognized badge is ignored. If the director says "only scan Building A and Building B," the team skips Building C entirely, even if qualified employees work there. That is what basePackages does in @ComponentScan.
Understanding the Concepts
What is @ComponentScan?
@ComponentScan is a Spring Framework annotation that tells the container which Java packages to search for classes that should become beans. When the container starts, it scans every class in the specified packages and their sub-packages, looking for stereotype annotations like @Component, @Service, @Repository, and @Controller.
If a class has one of these annotations, Spring creates a BeanDefinition for it and registers it in the application context.
package com.bank.core;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
@Configuration
@ComponentScan(basePackages = "com.bank.core")
class BankAppConfig {
}
@Service
class AccountService {
public String getStatus() {
return "AccountService is active";
}
}
public class ComponentScanBasicDemo {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(BankAppConfig.class);
var service = context.getBean(AccountService.class);
System.out.println(service.getStatus());
System.out.println("Bean count: " + context.getBeanDefinitionCount());
context.close();
}
}
Expected output:
AccountService is active
Bean count: 6
Why does @ComponentScan exist and why do we need it?
Without @ComponentScan, you would have to register every bean manually using @Bean methods in a @Configuration class. For a small app with 5 beans, that is manageable. For a banking application with 200 services, repositories, and controllers, manual registration is not practical.
@ComponentScan automates bean discovery. You annotate your classes, and the container finds them.
package com.bank.core;
public class WhyComponentScanExists {
public static void main(String[] args) {
System.out.println("Without @ComponentScan:");
System.out.println(" @Bean AccountService accountService() { return new AccountService(); }");
System.out.println(" @Bean LoanService loanService() { return new LoanService(); }");
System.out.println(" @Bean PaymentService paymentService() { ... }");
System.out.println(" ... repeat for every class");
System.out.println();
System.out.println("With @ComponentScan:");
System.out.println(" @ComponentScan(basePackages = \"com.bank\")");
System.out.println(" Spring finds all @Service, @Repository, @Controller automatically");
System.out.println(" Developer writes 1 line instead of 200 @Bean methods");
}
}
Expected output:
Without @ComponentScan:
@Bean AccountService accountService() { return new AccountService(); }
@Bean LoanService loanService() { return new LoanService(); }
@Bean PaymentService paymentService() { ... }
... repeat for every class
With @ComponentScan:
@ComponentScan(basePackages = "com.bank")
Spring finds all @Service, @Repository, @Controller automatically
Developer writes 1 line instead of 200 @Bean methods
How does @SpringBootApplication include @ComponentScan?
@SpringBootApplication is a composed annotation that combines three annotations: @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. When you place @SpringBootApplication on your main class, Spring scans the package of that class and all sub-packages.
This is why the Spring Boot convention is to put your main class in the root package (for example, com.bank), and all other classes in sub-packages like com.bank.service, com.bank.repository, com.bank.controller.
package com.bank;
public class SpringBootApplicationBreakdown {
public static void main(String[] args) {
System.out.println("@SpringBootApplication is equivalent to:");
System.out.println(" @SpringBootConfiguration (marks this as a config class)");
System.out.println(" @EnableAutoConfiguration (enables auto-config)");
System.out.println(" @ComponentScan (scans from this package down)");
System.out.println();
System.out.println("Main class in: com.bank");
System.out.println("Scanned packages:");
System.out.println(" com.bank (main class package)");
System.out.println(" com.bank.service (sub-package, scanned)");
System.out.println(" com.bank.repository(sub-package, scanned)");
System.out.println(" com.bank.controller(sub-package, scanned)");
System.out.println(" org.external.lib (NOT scanned, different root)");
}
}
Expected output:
@SpringBootApplication is equivalent to:
@SpringBootConfiguration (marks this as a config class)
@EnableAutoConfiguration (enables auto-config)
@ComponentScan (scans from this package down)
Main class in: com.bank
Scanned packages:
com.bank (main class package)
com.bank.service (sub-package, scanned)
com.bank.repository(sub-package, scanned)
com.bank.controller(sub-package, scanned)
org.external.lib (NOT scanned, different root)
How do you customize @ComponentScan with base packages and filters?
You can specify custom base packages, include filters, and exclude filters.
| Attribute | Purpose | Example |
|---|---|---|
| basePackages | Packages to scan | {"com.bank.service", "com.bank.repo"} |
| basePackageClasses | Type-safe package reference | {AccountService.class} |
| includeFilters | Only include matching classes | @Filter(type = ANNOTATION, classes = MyCustom.class) |
| excludeFilters | Exclude matching classes | @Filter(type = ASSIGNABLE_TYPE, classes = TestService.class) |
| FilterType.REGEX | Match by class name pattern | pattern = ".*Mock.*" |
| FilterType.ANNOTATION | Match by annotation | classes = Deprecated.class |
| FilterType.ASSIGNABLE_TYPE | Match by class/interface | classes = LegacyService.class |
package com.bank.core;
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.stereotype.Service;
@Service
class LoanService {
public String getName() { return "LoanService"; }
}
@Service
class MockPaymentService {
public String getName() { return "MockPaymentService"; }
}
@Configuration
@ComponentScan(
basePackages = "com.bank.core",
excludeFilters = @ComponentScan.Filter(
type = FilterType.REGEX,
pattern = ".*Mock.*"
)
)
class FilteredScanConfig {
}
public class ComponentScanFilterDemo {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(FilteredScanConfig.class);
String[] beanNames = context.getBeanDefinitionNames();
System.out.println("Registered beans (excluding Mock*):");
for (String name : beanNames) {
if (!name.startsWith("org.")) {
System.out.println(" " + name);
}
}
// LoanService is present, MockPaymentService is excluded
System.out.println("LoanService found: " + context.containsBean("loanService"));
System.out.println("MockPaymentService found: " + context.containsBean("mockPaymentService"));
context.close();
}
}
Expected output:
Registered beans (excluding Mock*):
filteredScanConfig
loanService
LoanService found: true
MockPaymentService found: false
What is a complete banking project showing scanning behavior?
This project has beans in three different packages. The main class is in com.bank, so sub-packages are scanned automatically. We also show what happens when a bean is outside the scan range.
Project structure
bank-scan-demo/
├── pom.xml
└── src/
└── main/
└── java/
├── com/
│ └── bank/
│ ├── BankScanDemoApp.java
│ ├── service/
│ │ └── PaymentService.java
│ ├── repository/
│ │ └── AccountRepository.java
│ └── controller/
│ └── PaymentController.java
└── org/
└── external/
└── FraudCheckService.java (outside com.bank)
pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>bank-scan-demosyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-websyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
AccountRepository.java
package com.bank.repository;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
import java.util.Map;
@Repository
public class AccountRepository {
private final Map<String, BigDecimal> balances = Map.of(
"SAV2001", new BigDecimal("150000.00"),
"CUR3001", new BigDecimal("500000.00")
);
public BigDecimal getBalance(String accountId) {
return balances.getOrDefault(accountId, BigDecimal.ZERO);
}
}
PaymentService.java
package com.bank.service;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class PaymentService {
private final AccountRepository accountRepository;
public PaymentService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public String checkBalance(String accountId) {
BigDecimal balance = accountRepository.getBalance(accountId);
return accountId + " balance: " + balance + " INR";
}
}
PaymentController.java
package com.bank.controller;
import com.bank.service.PaymentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PaymentController {
private final PaymentService paymentService;
public PaymentController(PaymentService paymentService) {
this.paymentService = paymentService;
}
@GetMapping("/balance/{accountId}")
public String balance(@PathVariable String accountId) {
return paymentService.checkBalance(accountId);
}
}
FraudCheckService.java (outside com.bank)
package org.external;
import org.springframework.stereotype.Service;
@Service
public class FraudCheckService {
public String check(String accountId) {
return "Fraud check passed for " + accountId;
}
}
BankScanDemoApp.java
package com.bank;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class BankScanDemoApp {
public static void main(String[] args) {
SpringApplication.run(BankScanDemoApp.class, args);
}
@Bean
CommandLineRunner showBeans(ApplicationContext ctx) {
return args -> {
System.out.println("--- Beans discovered by @ComponentScan ---");
System.out.println("paymentService found: " + ctx.containsBean("paymentService"));
System.out.println("accountRepository found: " + ctx.containsBean("accountRepository"));
System.out.println("paymentController found: " + ctx.containsBean("paymentController"));
System.out.println("fraudCheckService found: " + ctx.containsBean("fraudCheckService"));
System.out.println();
System.out.println("FraudCheckService is in org.external, outside com.bank.");
System.out.println("Spring did not scan org.external, so it was NOT discovered.");
};
}
}
Expected output:
--- Beans discovered by @ComponentScan ---
paymentService found: true
accountRepository found: true
paymentController found: true
fraudCheckService found: false
FraudCheckService is in org.external, outside com.bank.
Spring did not scan org.external, so it was NOT discovered.
How to fix: add the external package
package com.bank;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.bank", "org.external"})
public class BankScanDemoAppFixed {
// Now Spring scans both com.bank and org.external
}
Expected output after fix:
fraudCheckService found: true
How to run
cd bank-scan-demo
mvn clean package -DskipTests
java -jar target/bank-scan-demo-1.0.0.jar
# Test the endpoint
curl http://localhost:8080/balance/SAV2001
What are common mistakes with @ComponentScan?
Wrong: main class in a deep package
package com.bank.app.config.startup;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BankApplication {
public static void main(String[] args) {
SpringApplication.run(BankApplication.class, args);
}
}
Problem: main class is in com.bank.app.config.startup.
Spring scans com.bank.app.config.startup and its sub-packages only.
Classes in com.bank.service, com.bank.repository, com.bank.controller are NOT found.
Result: NoSuchBeanDefinitionException at startup.
Correct: main class in the root package
package com.bank;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BankApplication {
public static void main(String[] args) {
SpringApplication.run(BankApplication.class, args);
}
}
Correct: main class is in com.bank.
Spring scans com.bank and everything below it.
com.bank.service, com.bank.repository, com.bank.controller are all discovered.
Wrong: duplicate @ComponentScan overrides the default
package com.bank;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "org.external") // WRONG: this replaces the default scan
public class BankApplicationWrong {
// Now ONLY org.external is scanned.
// com.bank.service, com.bank.repository are NOT scanned!
}
Problem: adding @ComponentScan with basePackages REPLACES the default.
com.bank is no longer scanned. Only org.external is scanned.
Fix: include com.bank explicitly.
Correct: include both packages
package com.bank;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.bank", "org.external"})
public class BankApplicationCorrect {
// Both com.bank and org.external are scanned.
}
Correct: both packages are listed.
com.bank.service, com.bank.repository, and org.external are all scanned.
How does component scanning work internally?
At startup, Spring does not use Java reflection to scan classes. It uses ASM, a bytecode reading library, to read .class files directly from the classpath. This is faster because ASM reads metadata without loading classes into the JVM.
The steps are:
- The container resolves the base packages from @ComponentScan.
- It converts each package name to a classpath path (com.bank becomes com/bank).
- It scans all
.classfiles in those directories recursively. - For each
.classfile, ASM reads the annotations without loading the class. - If a class has a stereotype annotation, Spring creates a BeanDefinition.
- The BeanDefinition is registered in the BeanDefinitionRegistry.
- After all scanning is done, the container instantiates beans in dependency order.
package com.bank.core;
public class ScanningInternals {
public static void main(String[] args) {
System.out.println("Component scanning internals:");
System.out.println(" 1. Base package: com.bank");
System.out.println(" 2. Classpath path: com/bank/");
System.out.println(" 3. Found files:");
System.out.println(" com/bank/service/PaymentService.class");
System.out.println(" com/bank/repository/AccountRepository.class");
System.out.println(" com/bank/controller/PaymentController.class");
System.out.println(" 4. ASM reads annotations (no reflection yet)");
System.out.println(" 5. PaymentService has @Service -> create BeanDefinition");
System.out.println(" 6. AccountRepository has @Repository -> create BeanDefinition");
System.out.println(" 7. PaymentController has @Controller -> create BeanDefinition");
System.out.println(" 8. Register all BeanDefinitions");
System.out.println(" 9. Instantiate beans in dependency order");
}
}
Expected output:
Component scanning internals:
1. Base package: com.bank
2. Classpath path: com/bank/
3. Found files:
com/bank/service/PaymentService.class
com/bank/repository/AccountRepository.class
com/bank/controller/PaymentController.class
4. ASM reads annotations (no reflection yet)
5. PaymentService has @Service -> create BeanDefinition
6. AccountRepository has @Repository -> create BeanDefinition
7. PaymentController has @Controller -> create BeanDefinition
8. Register all BeanDefinitions
9. Instantiate beans in dependency order
What should a senior or principal engineer know?
At the senior level, you should understand the performance impact of component scanning and how to control it.
- Startup time: scanning hundreds of packages reads hundreds of
.classfiles from disk. In a microservice that needs fast cold starts (AWS Lambda, Kubernetes), this matters. Narrow your base packages. - Spring AOT (Ahead of Time): Spring Boot 3.x can generate bean definitions at compile time, eliminating runtime classpath scanning. This is used for GraalVM native images.
- spring.components index: the
spring-context-indexerannotation processor creates aMETA-INF/spring.componentsfile at compile time. The container reads this file instead of scanning the classpath. This speeds up startup for large applications. - Multiple @ComponentScan: you can have multiple @ComponentScan annotations on different @Configuration classes, but they share the same BeanDefinitionRegistry. A bean discovered by two scans is registered once.
- Conditional scanning: combine @ComponentScan with @Profile to scan different packages in different environments. For example, scan
com.bank.mockonly in the test profile.
package com.bank.core;
public class SeniorScanKnowledge {
public static void main(String[] args) {
System.out.println("Senior/Principal @ComponentScan Checklist:");
System.out.println(" 1. Narrow base packages for faster startup");
System.out.println(" 2. Spring AOT generates bean defs at compile time (native images)");
System.out.println(" 3. spring-context-indexer creates META-INF/spring.components");
System.out.println(" 4. ASM reads class files without loading them (faster than reflection)");
System.out.println(" 5. Multiple @ComponentScan on different configs share one registry");
System.out.println(" 6. Use @Profile + @ComponentScan for environment-specific beans");
System.out.println(" 7. Avoid scanning root package (e.g., com) as it scans all libraries");
}
}
Expected output:
Senior/Principal @ComponentScan Checklist:
1. Narrow base packages for faster startup
2. Spring AOT generates bean defs at compile time (native images)
3. spring-context-indexer creates META-INF/spring.components
4. ASM reads class files without loading them (faster than reflection)
5. Multiple @ComponentScan on different configs share one registry
6. Use @Profile + @ComponentScan for environment-specific beans
7. Avoid scanning root package (e.g., com) as it scans all libraries
What are common interview follow-up questions?
- What happens if you put @SpringBootApplication in a sub-package instead of the root? (Only that sub-package and below is scanned. Beans in sibling packages are not found.)
- Can you scan the same package twice? (Yes, but beans are registered once. No duplicates.)
- What is the difference between basePackages and basePackageClasses? (basePackages takes strings that can break during refactoring. basePackageClasses takes class references that the compiler checks.)
- How do you scan a third-party library's beans? (Add the library's package to basePackages. Or use @Import to bring in specific configuration classes from the library.)
- Does @ComponentScan find @Bean methods? (No. @ComponentScan finds classes with stereotype annotations. @Bean methods inside @Configuration classes are processed separately after the @Configuration class itself is discovered.)
- What is FilterType.CUSTOM? (You implement TypeFilter and write custom logic to decide whether a class should be included or excluded.)
Visual Overview
@ComponentScan Discovery Flow
===============================
┌──────────────────────────┐
│ @SpringBootApplication │
│ package: com.bank │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Component Scanner │
│ Base package: com.bank │
└────────────┬─────────────┘
│ Scan recursively
▼
┌─────────────────────────────────────────┐
│ Classpath: com/bank/ │
│ │
│ com/bank/service/ │
│ PaymentService.class -> @Service ✓ │
│ │
│ com/bank/repository/ │
│ AccountRepository.class -> @Repo ✓ │
│ │
│ com/bank/controller/ │
│ PaymentController.class -> @Rest ✓ │
│ │
│ org/external/ │
│ FraudCheckService.class -> @Service ✗ │
│ (outside com.bank, not scanned) │
└─────────────────────────────────────────┘
│
▼
┌──────────────────────────┐
│ BeanDefinitionRegistry │
│ paymentService │
│ accountRepository │
│ paymentController │
│ (3 beans registered) │
└──────────────────────────┘
Key Takeaway
@ComponentScan is how Spring discovers your beans automatically. Instead of registering every class manually with @Bean methods, you annotate your classes with @Service, @Repository, or @Controller, and @ComponentScan finds them by scanning the classpath.
In Spring Boot, @SpringBootApplication includes @ComponentScan by default. It scans the package of the main class and all sub-packages. This is why the convention is to place the main class in the root package, like com.bank, and everything else in sub-packages like com.bank.service and com.bank.repository.
In our National Bank of India scanning demo, we saw that beans in com.bank.service, com.bank.repository, and com.bank.controller were discovered automatically. But FraudCheckService in org.external was not found, because it was outside the base package. To fix it, we added org.external to the basePackages list.
The most common mistake is putting the main class in a deep sub-package, which limits the scan range. The second most common mistake is adding a custom @ComponentScan that replaces the default scan instead of extending it.
At the senior level, know that scanning uses ASM (not reflection) to read class metadata, that Spring AOT eliminates runtime scanning for native images, and that the spring-context-indexer can speed up startup for large applications.
Remember one sentence: @ComponentScan tells Spring which packages to search for annotated classes, and @SpringBootApplication scans the main class package and all sub-packages by default.
---