我发现我们有 @org.springframework.context.annotation.ComponentScans
和 @org.springframework.context.annotation.ComponentScan
。
- 我们如何使用
@ComponentScans()
? @ComponentScans()
和@ComponentScan({"com.org.abc", "com.org.xyz"})
有什么不同?
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
有什么优势吗?还是只是为了可读性? - NibyComponentScans
是一个容器注解,它聚合了多个 ComponentScan
注解。因此我认为我们不需要关心它,只需按照你的方式完成即可。 - Loc Le@ComponentScans()
。这只是Java <8在具有重复注释时解决限制的一种解决方法。不要使用它。” - Abbin VargheseComponentScans 是一个容器注解,聚合了多个 ComponentScan 注解。
ComponentScan 为 @Configuration 类配置组件扫描指令。
@ComponentScans({@ComponentScan("com.org.abc"), @ComponentScan("com.org.xyz")})
is equivalent to your example . In the code of theComponentScans
annotation, there is nothing more thanComponentScan[] value();
- ArnaudComponentScans
。它只是Java <8的限制的解决方法,用于重复注释。不要使用它。请注意,实际上这是一种模式,因此有很多注释都有复数版本,在Java8+中可以安全地忽略它们,您可以简单地重复这些注释。 - Giacomo Alzetta@ComponentScans()
:) - Abbin Varghese