00:00

Component Scanning in Spring

Last updated:

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.

Analogy: A new manager can either receive a printed staff list (explicit @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

How component scanning registers beansComponent scanning starts from one or more base packages. It lists the class files in those packages and their sub-packages, reads each class's annotations from the bytecode without loading the class, and keeps the classes that pass the include filters, by default those annotated with @Component or a stereotype, and are not removed by exclude filters. For each candidate it generates a bean name, resolves the scope, and registers a bean definition. Conditions such as @Profile and @ConditionalOnProperty are checked before registration. Base packages com.javabytechie.shop and sub-packages Read metadata annotations from bytecode (no loading) Filters include @Component; apply excludes Conditions @Profile, @Conditional... Bean definition registered Interfaces, abstract classes (without @Lookup methods) and classes without a stereotype are skipped. Happens once, while the context refreshes, before any bean is created.
Scanning reads class metadata, applies filters and conditions, and registers a bean definition for each match.
  1. Start from base packages. Spring lists all .class files in each base package and its sub-packages, including those inside JAR files.
  2. Read metadata without loading classes. Spring reads annotations straight from the bytecode, which is faster and avoids running static initializers.
  3. Apply filters. The default include filter accepts classes annotated (directly or through a meta-annotation) with @Component. Exclude filters remove matches.
  4. Check conditions. @Profile and @Conditional annotations on the class decide whether it is registered.
  5. 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

AnnotationMeaningExtra behavior
@ComponentGeneric Spring-managed classNone
@ServiceBusiness logicNone; documents intent
@RepositoryData accessPersistence exceptions are translated to DataAccessException
@Controller / @RestControllerWeb endpointsDetected by Spring MVC as request handlers
@ControllerAdvice / @RestControllerAdviceGlobal web exception handlingApplied to controllers
@ConfigurationHolds @Bean methodsIts @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:

  • TypeExcludeFilter lets Spring Boot and test slices hide classes from scanning. @WebMvcTest, for example, uses it so only web components are registered.
  • AutoConfigurationExcludeFilter stops 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:

ShopApplication.java
@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.

Entities and repositories: scanning settings do not change where JPA entities and Spring Data repositories are found. For those, use @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:

FilterTypeMatchesExample
ANNOTATION (default)Classes with an annotation@Filter(Deprecated.class)
ASSIGNABLE_TYPEClasses of a type or its subtypes@Filter(type = ASSIGNABLE_TYPE, classes = LegacyGateway.class)
REGEXFully qualified class names matching a regular expressionpattern = "com\\.javabytechie\\.shop\\.legacy\\..*"
ASPECTJAn AspectJ type patternpattern = "com.javabytechie..*Stub"
CUSTOMYour own TypeFilter implementationclasses = 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:

ShopApplication.java (with an exclude filter)
@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:

Console
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

AuditLogger.java
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

UseCase.java
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 "";
}
PlaceOrderUseCase.java
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

ShopApplication.java
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");
        };
    }
}
Console
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

ApproachBest forDrawback
Component scanningYour own application classesRegistration is implicit; easy to scan too much or too little
@Bean methodsThird-party classes and beans that need setup codeMore code per bean
@Import(SomeConfig.class)Pulling in a specific configuration from a libraryCallers must know the class name
Auto-configurationLibraries that should configure themselves when addedMore 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

SymptomLikely causeFix
"required a bean of type ... that could not be found"Class outside the scanned packages, or missing annotationMove it under the root package, add the annotation, or add its package
Endpoint returns 404 although the controller existsController not scannedSame as above; check the main class's package
Bean exists twice, or a @Configuration runs twiceOverlapping base packages or an extra @ComponentScanUse one scan definition with non-overlapping packages
Test slice loads unexpected beansA custom @ComponentScan without TypeExcludeFilterKeep Spring Boot's filters when declaring your own scan
ConflictingBeanDefinitionExceptionTwo classes with the same simple nameExplicit names or a fully qualified name generator
Slow startup in a huge code baseVery broad base packages, such as comNarrow the packages; never scan the default package
Version note: Older Spring versions offered a build-time "candidate components index" (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 scanBasePackageClasses instead of package strings when you must add packages.
  • Keep Spring Boot's filters whenever you declare @ComponentScan yourself.
  • 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