Component Scanning in Spring
Component scanning in Spring is how the container discovers your classes without a list of beans written by hand. At startup Spring looks through chosen packages for classes marked with @Component or one of its specializations, such as @Service and @RestController, and registers a bean for each one. In Spring Boot, @SpringBootApplication switches it on for you, which is why adding @Service to a class is usually all it takes to make it injectable.
This tutorial explains how scanning works, which annotations it detects, how Spring Boot configures it, and how to scan extra packages, exclude classes, name beans and create your own stereotype annotations. It finishes with the most common scanning problems and how to fix them.
1. What Is Component Scanning?
Component scanning is the automatic search for bean classes on the classpath. Instead of declaring every service in a configuration class, you annotate the class itself, and Spring finds it. The result is the same as a @Bean method: a bean definition that the IoC container uses to create and inject the object.
@Bean methods) or walk through the floors and note everyone wearing a company badge (scanning). The badge is the annotation, and the floors visited are the base packages.2. How Component Scanning Works
- Start from base packages. Spring lists all
.classfiles in each base package and its sub-packages, including those inside JAR files. - Read metadata without loading classes. Spring reads annotations straight from the bytecode, which is faster and avoids running static initializers.
- Apply filters. The default include filter accepts classes annotated (directly or through a meta-annotation) with
@Component. Exclude filters remove matches. - Check conditions.
@Profileand@Conditionalannotations on the class decide whether it is registered. - Register bean definitions with a generated name and the scope from
@Scope, singleton by default.
Only concrete, independent classes qualify: interfaces, plain abstract classes and non-static inner classes are skipped. Spring Data repository interfaces are found by a separate mechanism, not by component scanning.
3. Annotations That Scanning Detects
| Annotation | Meaning | Extra behavior |
|---|---|---|
@Component | Generic Spring-managed class | None |
@Service | Business logic | None; documents intent |
@Repository | Data access | Persistence exceptions are translated to DataAccessException |
@Controller / @RestController | Web endpoints | Detected by Spring MVC as request handlers |
@ControllerAdvice / @RestControllerAdvice | Global web exception handling | Applied to controllers |
@Configuration | Holds @Bean methods | Its @Bean methods are processed too |
All of them are annotated with @Component themselves. That is called a meta-annotation, and it is why scanning finds them all, and why you can create your own stereotypes (section 8).
4. Component Scanning in Spring Boot
@SpringBootApplication contains @ComponentScan with no base package, which means "the package of this class and everything below it". It also adds two exclude filters:
TypeExcludeFilterlets Spring Boot and test slices hide classes from scanning.@WebMvcTest, for example, uses it so only web components are registered.AutoConfigurationExcludeFilterstops auto-configuration classes that happen to sit in your packages from being scanned as normal configuration.
This is why the main class belongs in the root package; see Spring Boot project structure.
5. Scanning Additional Packages
When components live outside the main class's package, for example in a shared company library, add their packages. Use the attributes on @SpringBootApplication so Spring Boot's filters stay in place:
@SpringBootApplication(scanBasePackageClasses = { ShopApplication.class, AuditLogger.class })
public class ShopApplication {
// ...
}
scanBasePackageClasses uses a class from each package as a marker. It is safer than scanBasePackages = "com.javabytechie.common", because a package rename breaks the compiler instead of silently breaking scanning. Note that the list replaces the default, so include the main class's own package.
@EntityScan and @EnableJpaRepositories. In Spring Boot 4, @EntityScan moved to the org.springframework.boot.persistence.autoconfigure package.6. Including and Excluding Classes with Filters
@ComponentScan accepts includeFilters and excludeFilters of five types:
FilterType | Matches | Example |
|---|---|---|
ANNOTATION (default) | Classes with an annotation | @Filter(Deprecated.class) |
ASSIGNABLE_TYPE | Classes of a type or its subtypes | @Filter(type = ASSIGNABLE_TYPE, classes = LegacyGateway.class) |
REGEX | Fully qualified class names matching a regular expression | pattern = "com\\.javabytechie\\.shop\\.legacy\\..*" |
ASPECTJ | An AspectJ type pattern | pattern = "com.javabytechie..*Stub" |
CUSTOM | Your own TypeFilter implementation | classes = MyTypeFilter.class |
@SpringBootApplication has no filter attributes, so to exclude a package you replace it with its three parts and keep Spring Boot's filters:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class),
@Filter(type = FilterType.REGEX, pattern = "com\\.javabytechie\\.shop\\.legacy\\..*") })
public class ShopApplication {
// ...
}
Often a condition on the class is simpler than a filter: @Profile("!prod") or @ConditionalOnProperty(name = "shop.legacy.enabled", havingValue = "true") keeps the decision next to the class and makes it configurable.
7. Bean Names and Name Conflicts
A scanned bean is named after its simple class name with the first letter lower-cased: OrderService becomes orderService. If the first two letters are upper case, the name is kept as is, so URLShortener stays URLShortener. You can set a name explicitly: @Service("checkoutOrders").
Two classes with the same simple name in different packages produce the same bean name, and startup fails:
ConflictingBeanDefinitionException: Annotation-specified bean name 'orderMapper' for bean class
[com.javabytechie.shop.billing.OrderMapper] conflicts with existing, non-compatible bean definition
of same name and class [com.javabytechie.shop.order.OrderMapper]
Fix it by giving one bean an explicit name, renaming one class, or, if conflicts are common in a large code base, setting nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class on @ComponentScan (or @SpringBootApplication) so names include the package.
8. A Complete Example: Shared Library and Custom Stereotype
The shop uses an audit component from a shared library in com.javabytechie.common and introduces a @UseCase stereotype for application services.
8.1 A Component in Another Package
package com.javabytechie.common.audit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class AuditLogger {
private static final Logger log = LoggerFactory.getLogger(AuditLogger.class);
public void record(String action, String subject) {
log.info("AUDIT {} {}", action, subject);
}
}
8.2 A Custom Stereotype
package com.javabytechie.shop.shared;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Service;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Service
public @interface UseCase {
@AliasFor(annotation = Service.class)
String value() default "";
}
package com.javabytechie.shop.order;
import com.javabytechie.common.audit.AuditLogger;
import com.javabytechie.shop.shared.UseCase;
@UseCase
public class PlaceOrderUseCase {
private final AuditLogger audit;
public PlaceOrderUseCase(AuditLogger audit) {
this.audit = audit;
}
public void place(String orderId) {
audit.record("ORDER_PLACED", orderId);
}
}
8.3 The Main Class
package com.javabytechie.shop;
import com.javabytechie.common.audit.AuditLogger;
import com.javabytechie.shop.order.PlaceOrderUseCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication(scanBasePackageClasses = { ShopApplication.class, AuditLogger.class })
public class ShopApplication {
private static final Logger log = LoggerFactory.getLogger(ShopApplication.class);
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
@Bean
ApplicationRunner scanReport(ApplicationContext context, PlaceOrderUseCase placeOrder) {
return args -> {
log.info("auditLogger registered: {}", context.containsBean("auditLogger"));
log.info("placeOrderUseCase registered: {}", context.containsBean("placeOrderUseCase"));
placeOrder.place("ORD-2001");
};
}
}
auditLogger registered: true
placeOrderUseCase registered: true
AUDIT ORDER_PLACED ORD-2001
Remove AuditLogger.class from scanBasePackageClasses and startup fails, because PlaceOrderUseCase needs a bean that is no longer scanned. The @UseCase annotation works because it is meta-annotated with @Service, which is meta-annotated with @Component.
9. Component Scanning vs @Bean and @Import
| Approach | Best for | Drawback |
|---|---|---|
| Component scanning | Your own application classes | Registration is implicit; easy to scan too much or too little |
@Bean methods | Third-party classes and beans that need setup code | More code per bean |
@Import(SomeConfig.class) | Pulling in a specific configuration from a library | Callers must know the class name |
| Auto-configuration | Libraries that should configure themselves when added | More work for the library author |
For shared libraries used by many services, auto-configuration or an explicit @Import is usually better than asking every application to scan the library's packages; see auto-configuration.
10. How to Fix Common Scanning Problems
| Symptom | Likely cause | Fix |
|---|---|---|
| "required a bean of type ... that could not be found" | Class outside the scanned packages, or missing annotation | Move it under the root package, add the annotation, or add its package |
| Endpoint returns 404 although the controller exists | Controller not scanned | Same as above; check the main class's package |
Bean exists twice, or a @Configuration runs twice | Overlapping base packages or an extra @ComponentScan | Use one scan definition with non-overlapping packages |
| Test slice loads unexpected beans | A custom @ComponentScan without TypeExcludeFilter | Keep Spring Boot's filters when declaring your own scan |
ConflictingBeanDefinitionException | Two classes with the same simple name | Explicit names or a fully qualified name generator |
| Slow startup in a huge code base | Very broad base packages, such as com | Narrow the packages; never scan the default package |
spring-context-indexer) to speed up scanning. It is deprecated; Spring's ahead-of-time processing and GraalVM native images are the supported ways to reduce startup work today.11. Best Practices
- Keep everything under the main class's package so the default scan is all you need.
- Use
scanBasePackageClassesinstead of package strings when you must add packages. - Keep Spring Boot's filters whenever you declare
@ComponentScanyourself. - Use the specific stereotype (
@Service,@Repository) for readability and, for repositories, exception translation. - Prefer conditions over exclude filters to switch components on and off.
- Expose libraries through auto-configuration instead of requiring consumers to scan them.
12. Summary
Component scanning in Spring searches base packages for classes annotated with @Component or a stereotype built on it, applies include and exclude filters and conditions, and registers a bean definition for each match. Spring Boot's @SpringBootApplication scans the main class's package and sub-packages with two exclude filters of its own. Add packages with scanBasePackageClasses, exclude classes with filters or, more simply, conditions, resolve name clashes with explicit names, and create stereotypes such as @UseCase through meta-annotations. Keep the main class at the root and libraries behind auto-configuration, and scanning stays invisible.
13. References
Component Scanning in Spring Interview Questions and Answers
Common interview questions on Component Scanning in Spring, from basic to scenario-based, with short answers you can explain in your own words.
Q. What does component scanning do, and which classes does it register?
Answer: It searches the base packages and their sub-packages for concrete classes annotated with @Component, directly or through a meta-annotation such as @Service, @Repository, @Controller or @Configuration. Matching classes that pass the filters and conditions get a bean definition. Interfaces and plain abstract classes are skipped.
Q. How does @SpringBootApplication configure scanning, and how do you scan an extra package?
Answer: It scans the main class's package and everything below it, with TypeExcludeFilter and AutoConfigurationExcludeFilter as exclude filters. To add a package, set scanBasePackageClasses (or scanBasePackages) on @SpringBootApplication, listing the main package too, because the attribute replaces the default. JPA entities and repositories need @EntityScan and @EnableJpaRepositories instead.
Q. How do you exclude one class or package from component scanning?
Answer: Use an exclude filter on @ComponentScan, by annotation, assignable type, regular expression, AspectJ pattern or a custom TypeFilter. In Spring Boot you must declare @ComponentScan yourself and keep Boot's two filters, since @SpringBootApplication has no filter attribute. Often a better option is a condition on the class, such as @Profile or @ConditionalOnProperty.
Q. What name does a scanned bean get, and how do you fix a ConflictingBeanDefinitionException?
Answer: The simple class name with the first letter lower-cased, unless the first two letters are upper case. Two classes with the same simple name in different packages get the same name and cause ConflictingBeanDefinitionException. Give one an explicit name such as @Component("billingOrderMapper"), rename a class, or use FullyQualifiedAnnotationBeanNameGenerator as the scan's name generator.
Q. How do you create a custom stereotype annotation?
Answer: Declare a runtime-retained annotation for types and annotate it with @Component or a specialization such as @Service. Scanning follows meta-annotations, so classes carrying the new annotation become beans. Add a value attribute with @AliasFor(annotation = Service.class) if users should be able to set the bean name.
Q. After adding @ComponentScan("com.javabytechie") to the main class, @WebMvcTest tests start loading services and repositories. Why?
Answer: The explicit @ComponentScan replaced the one inside @SpringBootApplication, and it lacks TypeExcludeFilter, the filter test slices use to hide non-web components. Now every component is scanned in slice tests too. Remove the extra annotation and use scanBasePackageClasses, or declare the scan with Spring Boot's exclude filters included.