@ComponentScans和@ComponentScan有什么区别?

Abb*_*ese 4 java spring

我知道我们有@org.springframework.context.annotation.ComponentScans@org.springframework.context.annotation.ComponentScan

  1. 我们如何使用@ComponentScans()
  2. 有什么@ComponentScans()不同@ComponentScan({"com.org.abc", "com.org.xyz"})

Loc*_* Le 5

如果启用了组件扫描,Spring可以自动在软件包中扫描bean。

@ComponentScan使用注释配置来配置要扫描类的软件包。我们可以直接使用basePackages或value参数之一指定基本包名称(value是basePackages的别名)

@Configuration
@ComponentScan(basePackages = "com.baeldung.annotations")
class VehicleFactoryConfig {}
Run Code Online (Sandbox Code Playgroud)

同样,我们可以使用以下basePackageClasses参数指向基本包中的类 :

@Configuration
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}
Run Code Online (Sandbox Code Playgroud)

这两个参数都是数组,因此我们可以为每个参数提供多个包。

如果未指定任何参数,则从@ComponentScan存在带注释的类的同一包中进行扫描。

@ComponentScan利用Java 8重复注释功能,这意味着我们可以用它多次标记一个类:

@Configuration
@ComponentScan(basePackages = "com.baeldung.annotations")
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}
Run Code Online (Sandbox Code Playgroud)

另外,我们可以@ComponentScans用来指定多个 @ComponentScan配置:

@Configuration
@ComponentScans({ 
    @ComponentScan(basePackages = "com.baeldung.annotations"), 
    @ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
})
class VehicleFactoryConfig {}
Run Code Online (Sandbox Code Playgroud)

您可以找到更多的Spring Bean注释