【问题标题】:@DataJpaTest: how to stop loading unneeded @ConfigurationProperties@DataJpaTest:如何停止加载不需要的 @ConfigurationProperties
【发布时间】:2020-04-03 08:13:53
【问题描述】:

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

测试:

@DataJpaTest
public class FooCustomerServiceTest
{
    @Autowired
    FooCustomerRepository repo;

    @Test
    void findAll()
    {
       repo.findAll();
    }
}

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

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

foo.appconfig.AppInfoConfig

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

    ...
}

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

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

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

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

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

注意:@TestConfiguration 具有 @Bean 方法确实有效,但如果您有很多 @ConfigurationProperties 类,则不是很方便。

【问题讨论】:

    标签: java spring-boot testing spring-data-jpa configurationproperties


    【解决方案1】:

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

    更多详情请见the documentation

    【讨论】:

    • 谢谢您,先生。你节省了我的时间。
    【解决方案2】:

    我正在分享我的经历。

    我的问题与 OP 解释的完全一样,而且问题的原因也与接受的答案相同。

    但就我而言,@ComponentScan 是必需的,因为应用程序需要扫描应用程序包之外的组件。

    @ComponentScan(
            basePackageClasses = {
                    Application.class, // this application
                    some.other.NoOp.class // resides in a dependency
            }
    )
    @SpringBootApplication
    class MyApplication {
    }
    

    我花了几个小时我的@DataJpaTest 出了什么问题,甚至偷看了这个帖子。

    我的解决方案是使用自定义上下文替换主应用程序。

    @EnableAutoConfiguration
    @SpringBootConfiguration
    @Slf4j
    class MyDataJpaTestConfiguration {
    
    }
    

    然后从 @DataJpaTest 类中导入它。

    @Import(MyDataJpaTestConfiguration.class)
    @DataJpaTest
    abstract class MyEntityDataJpaTest {
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2016-09-08
      • 1970-01-01
      • 2021-09-21
      • 2012-01-24
      相关资源
      最近更新 更多