@ComponentScans和@ComponentScan有什么区别?

8

我发现我们有 @org.springframework.context.annotation.ComponentScans@org.springframework.context.annotation.ComponentScan

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

1
@ComponentScan可以包含很多嵌套的@ComponentScan,对吧?https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScans.html - vikingsteve
2
@ComponentScans({@ComponentScan("com.org.abc"), @ComponentScan("com.org.xyz")}) is equivalent to your example . In the code of the ComponentScans annotation, there is nothing more than ComponentScan[] value(); - Arnaud
3
如果您正在使用Java 8,则永远不需要使用 ComponentScans。它只是Java <8的限制的解决方法,用于重复注释。不要使用它。请注意,实际上这是一种模式,因此有很多注释都有复数版本,在Java8+中可以安全地忽略它们,您可以简单地重复这些注释。 - Giacomo Alzetta
谢谢大家。很明显我不需要使用@ComponentScans() :) - Abbin Varghese
2个回答

10

Spring can automatically scan a package for beans if component scanning is enabled.

@ComponentScan configures which packages to scan for classes with annotation configuration. We can specify the base package names directly with one of the basePackages or value arguments (value is an alias for basePackages)

@Configuration
@ComponentScan(basePackages = "com.baeldung.annotations")
class VehicleFactoryConfig {}

Also, we can point to classes in the base packages with the basePackageClasses argument:

@Configuration
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}

Both arguments are arrays so that we can provide multiple packages for each.

If no argument is specified, the scanning happens from the same package where the @ComponentScan annotated class is present.

@ComponentScan leverages the Java 8 repeating annotations feature, which means we can mark a class with it multiple times:

@Configuration
@ComponentScan(basePackages = "com.baeldung.annotations")
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}

Alternatively, we can use @ComponentScans to specify multiple @ComponentScan configurations:

@Configuration
@ComponentScans({ 
    @ComponentScan(basePackages = "com.baeldung.annotations"), 
    @ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
})
class VehicleFactoryConfig {}

你可以找到更多的Spring Bean注解


那么使用 ComponentScans 有什么优势吗?还是只是为了可读性? - Niby
ComponentScans 是一个容器注解,它聚合了多个 ComponentScan 注解。因此我认为我们不需要关心它,只需按照你的方式完成即可。 - Loc Le
正如@Giacomo所说:“如果您正在使用Java 8,您永远不需要使用@ComponentScans()。这只是Java <8在具有重复注释时解决限制的一种解决方法。不要使用它。” - Abbin Varghese

2
请查看文档:

ComponentScans 是一个容器注解,聚合了多个 ComponentScan 注解。

ComponentScan 为 @Configuration 类配置组件扫描指令。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接