spring-boot @ComponentScan


Example

You can use @ComponentScan in order to configure more complex package scanning. There is also @ComponentScans that act as a container annotation that aggregates several @ComponentScan annotations.

Basic code examples

@ComponentScan
public class DemoAutoConfiguration {
}

@ComponentScans({@ComponentScan("com.example1"), @ComponentScan("com.example2")})
public class DemoAutoConfiguration {
}

Stating @ComponentScan with no configuration acts like @SpringBootApplication and scans all packages under the class annotated with this annotation.

In this example I will state some of the useful attributes of @ComponentScan:

  1. basePackages - can be used to state specific packages to scan.
  2. useDefaultFilters - by setting this attribute to false (defaults true) you can make sure spring does not scan @Component, @Repository, @Service, or @Controller automatically.
  3. includeFilters - can be used to include specific spring annotations / regex patterns to include in package scanning.
  4. excludeFilters - can be used to exclude specific spring annotations / regex patterns to include in package scanning.

There are many more attributes but those are the most commonly used in order to customize package scanning.