@DataJpaTest:如何停止加载不需要的 @ConfigurationProperties

Ale*_*lex 2 java testing spring-data-jpa spring-boot configurationproperties

在 SpringBoot (2.2.1,2.2.2) 应用程序中,切片的 @DataJpaTest 不会运行,因为无法创建持有 @ConfigurationProperties 的 bean。

考试:

@DataJpaTest
public class FooCustomerServiceTest
{
    @Autowired
    FooCustomerRepository repo;

    @Test
    void findAll()
    {
       repo.findAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行测试时,我得到一个

没有可用的“foo.appconfig.AppInfoConfig”类型的合格 bean

foo.appconfig.AppInfoConfig

@ConfigurationProperties(prefix = "app.info")
public class AppInfoConfig
{
    private String name;

    ...
}
Run Code Online (Sandbox Code Playgroud)

它被一个@Component与测试无关的人引用。

foo.Application所使用没有特殊注释

@SpringBootApplication
@ComponentScan
@ConfigurationPropertiesScan
public class Application
{
    public static void main( final String[] args )
    {
        SpringApplication.run( Application.class, args );
    }
}
Run Code Online (Sandbox Code Playgroud)

由于切片测试仅扫描某些组件(@Entity 和 @Repository,在@DataJpaTest 的情况下)不扫描“AppInfoConfig”。没关系,但为什么要尝试将它注入到另一个既不是实体也不是存储库的控制器?

如何启用 AppInfoConfig 的正确创建或完全禁用创建?

注意:@TestConfiguration有一个@Bean方法确实有效,但如果你有很多这样的@ConfigurationProperties类就不是很方便了。

Ste*_*oll 5

为什么你有@ComponentScan你的SpringBootApplication?这样做会覆盖对其应用的配置,包括在切片测试中自定义类路径扫描的过滤器。

有关更多详细信息,请参阅文档