gpt4 book ai didi

java - Spring @ComponentScan 注释不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:15:56 25 4
gpt4 key购买 nike

我有带有包布局的 spring boot 应用程序示例:

main:
-com.foo
Application.java
-com.foo.services
ItemService.java
ItemRepository.java
-com.foo.config
Configuration.java
test:
-com.foo.services
ItemServiceIngegrationTest.java

我的集成测试运行失败,无法找到 ItemRepository bean如果放

  @ComponentScan(basePackageClasses = { ItemService.class })

但如果我把它工作

  @ComponentScan(basePackageClasses = { Application.class })

诀窍在哪里?

规范说:

Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

@EnableAutoConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Configuration.class })
public class ItemServiceIntegrationTest {
. . .
}

@org.springframework.context.annotation.Configuration
@PropertySource("classpath:application.properties")
@ComponentScan(basePackageClasses = { ItemService.class })
public class Configuration extends AbstractMongoConfiguration {
. . .
}

最佳答案

javadoc 说:

If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

因此,除非定义了特定的包类,否则它会从声明 ComponentScan 的包开始扫描。你能把它放在 Application 类中吗?

关于java - Spring @ComponentScan 注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35532311/

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