spring-boot Package scanning @SpringBootApplication


Example

The most basic way to structure your code using spring boot for good automatic package scanning is using @SpringBootApplication annotation. This annotation provide in itself 3 other annotations that helps with automatic scanning: @SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan (more info about each annotation in the Parameters section).

@SpringBootApplication will usualy be placed in the main package and all other components will be placed in packages under this file:

com
 +- example
     +- myproject
         +- Application.java (annotated with @SpringBootApplication)
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

Unless mentioned otherwise, spring boot detects @Configuration, @Component, @Repository, @Service, @Controller, @RestController annotations automatically under the scanned packages (@Configuration and @RestController are being picked because they are annotated by @Component and @Controller accordingly).

Basic Code example:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
}

Setting packages/classes explicitly

Since version 1.3 you can also tell spring boot to scan specific packages by setting scanBasePackages or scanBasePackageClasses in @SpringBootApplication instead of specifying @ComponentScan.

  1. @SpringBootApplication(scanBasePackages = "com.example.myproject") - set com.example.myproject as the base package to scan.
  2. @SpringBootApplication(scanBasePackageClasses = CustomerController.class) - type-safe alternative to scanBasePackages sets the package of CustomerController.java, com.example.myproject.web, as the base package to scan.

Excluding auto-configuration

Another important feature is the ability to exclude specific auto-configuration classes using exclude or excludeName (excludeName exist since version 1.3).

  1. @SpringBootApplication(exclude = DemoConfiguration.class) - will exclude DemoConfiguration from auto package scanning.
  2. @SpringBootApplication(excludeName = "DemoConfiguration") - will do the same using class fully classified name.