gpt4 book ai didi

java - @ComponentScans 和@ComponentScan 有什么区别?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:38:03 26 4
gpt4 key购买 nike

我看到我们有 @org.springframework.context.annotation.ComponentScans@org.springframework.context.annotation.ComponentScan

  1. 我们如何使用 @ComponentScans()
  2. @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 Annotations

关于java - @ComponentScans 和@ComponentScan 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52421944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com