Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring @ComponentScan Annotation with Example

The @ComponentScan annotation in Spring is used with the @Configuration annotation to specify the packages to scan for annotated components. @ComponentScan will scan for @Component, @Repository, @Service, @Controller, and other annotations to discover Spring beans automatically.

When you use @ComponentScan, Spring will scan the specified package and its sub-packages to detect classes annotated with the above stereotypes and automatically register them as beans in the application context.

Example:

  1. Setting up a few Components:

    Create a few classes and annotate them.

    package com.example.service;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class HelloWorldService {
        public String sayHello() {
            return "Hello from HelloWorldService!";
        }
    }
    
    package com.example.repository;
    
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class UserRepo {
        // ... some repository methods
    }
    
  2. Using the @ComponentScan Annotation:

    Now, to pick up the above beans and any others in the com.example package or its sub-packages:

    package com.example.config;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan(basePackages = "com.example")
    public class AppConfig {
        // Additional beans can be defined here if necessary
    }
    

    The basePackages attribute specifies the root package from which to start scanning. All sub-packages will be included in the scan.

  3. Bootstrap the Application:

    For a standalone application, use the AnnotationConfigApplicationContext:

    package com.example;
    
    import com.example.config.AppConfig;
    import com.example.service.HelloWorldService;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class Application {
        public static void main(String[] args) {
            ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
            HelloWorldService service = context.getBean(HelloWorldService.class);
            System.out.println(service.sayHello());
        }
    }
    

    When you run the Application class, you'll see the message from the HelloWorldService printed on the console.

A Few More Points:

  • Specifying Multiple Packages: You can specify multiple packages to scan by providing an array of package names to basePackages.

    @ComponentScan(basePackages = {"com.example.services", "com.example.repositories"})
    
  • Using basePackageClasses: Alternatively, you can use basePackageClasses to specify one or more classes that are located within the packages you want to scan. Spring will use the package of the given class as a starting point.

    @ComponentScan(basePackageClasses = HelloWorldService.class)
    

    This is type-safe and refactor-friendly compared to string package names.

  • Filters: You can include or exclude specific components using filters.

    @ComponentScan(basePackages = "com.example",
                   excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = SomeClassToExclude.class))
    

The @ComponentScan annotation provides a flexible way to specify which packages Spring should scan to detect and register beans automatically.

  1. Using @ComponentScan annotation in Spring:

    • The @ComponentScan annotation enables automatic detection and registration of Spring components.
    // AppConfig.java
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan("com.example")
    public class AppConfig {
        // Configuration details...
    }
    
  2. Spring @ComponentScan example project:

    • Create a simple Spring project demonstrating the usage of @ComponentScan.
    // ExampleComponent.java
    import org.springframework.stereotype.Component;
    
    @Component
    public class ExampleComponent {
        // Component logic...
    }
    
    // MainApplication.java
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class MainApplication {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.example");
            ExampleComponent exampleComponent = context.getBean(ExampleComponent.class);
            // Use exampleComponent...
            context.close();
        }
    }
    
  3. Scanning and detecting components with @ComponentScan in Spring:

    • Use @ComponentScan to scan and detect components within specified base packages.
    // AppConfig.java
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan("com.example")
    public class AppConfig {
        // Configuration details...
    }
    
  4. Customizing component scanning in Spring using @ComponentScan:

    • Customize component scanning by specifying additional configuration options within @ComponentScan.
    // AppConfig.java
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan(
        basePackages = "com.example",
        useDefaultFilters = false,
        includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = CustomComponent.class)
    )
    public class AppConfig {
        // Configuration details...
    }
    
  5. How to specify base packages with @ComponentScan in Spring:

    • Specify base packages for component scanning using the basePackages attribute.
    // AppConfig.java
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan(basePackages = {"com.example", "com.other"})
    public class AppConfig {
        // Configuration details...
    }
    
  6. Excluding packages from component scanning with @ComponentScan:

    • Exclude specific packages from component scanning using the excludeFilters attribute.
    // AppConfig.java
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan(basePackages = "com.example", excludeFilters = @ComponentScan.Filter(pattern = "com.example.exclude.*"))
    public class AppConfig {
        // Configuration details...
    }
    
  7. Spring @ComponentScan filter types and examples:

    • Use different filter types with @ComponentScan to include or exclude components based on specific criteria.
    // AppConfig.java
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.FilterType;
    
    @Configuration
    @ComponentScan(
        basePackages = "com.example",
        includeFilters = {
            @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {IncludeComponent.class}),
            @ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*RegexComponent$")
        },
        excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = ExcludeComponent.class)
    )
    public class AppConfig {
        // Configuration details...
    }
    
  8. Configuring @ComponentScan in Spring Boot:

    • Configure @ComponentScan in a Spring Boot application.
    // MyBootApplication.java
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class MyBootApplication {
        public static void main(String[] args) {
            SpringApplication.run(MyBootApplication.class, args);
        }
    }