Hands-On High Performance with Spring 5
上QQ阅读APP看书,第一时间看更新

The @ComponentScan annotation

Spring needs to know which packages contain Spring beans, otherwise, you would have to register each bean inpidually. That's what @ComponentScan is used for. In Spring, component scanning is not enabled by default. We need to enable it with the @ComponentScan annotation. This annotation is used with the @Configuration annotation to allow Spring to know the packages to scan for annotated components and to create beans from them. Let's look at the following simple example of @ComponentScan:

@Configuration
@ComponentScan(basePackages="com.packt.springhighperformance.ch2.bankingapp.model")
public class AppConfig {

}

In the @ComponentScan annotation, if the basePackages attribute is not defined, then scanning will occur from the package of the class that declares this annotation. In the preceding example, Spring will scan all classes of com.packt.springhighperformance.ch2.bankingapp.model, and the subpackage of that package. The basePackages attribute can accept an array of strings, which means that we can define multiple base packages to scan component classes in the application. Let's look at an example of how we can declare multiple packages in the basePackage attribute:

@Configuration
@ComponentScan(basePackages={"com.packt.springhighperformance.ch2.bankingapp.model","com.packt.springhighperformance.ch2.bankingapp.service"})
public class AppConfig {

}