Spring Boot:在测试中加载所有实现接口的bean?

huangapple go评论51阅读模式
英文:

Spring Boot: load all beans implementing an interface in test?

问题

我有一些接口 Filter,以及一些实现了这个接口的实现类。

@Test 中,我想要加载所有实现了 Filter 接口的 Bean。

目前,我必须显式地声明它们。例如:

@ContextConfiguration(classes = {FilterA.class, FilterB.class})

问题是:引入另一个 Filter 接口的实现类将需要在每个使用了这些 filters 的测试类中都进行添加。

有没有更好的方法呢?

英文:

I have some interface Filter and some implementations of this interface.

In @Test, I'd like to load all beans implementing Filter.

Currently, I have to declare them explicitly. For example:

@ContextConfiguration(classes = {FilterA.class, FilterB.class})

The problem: Introducing another Filter would require adding it for each test class that uses the filters.

Is there a better way?

答案1

得分: 3

添加一个 TestConfiguration,并在配置中声明所有实现该接口的 bean。然后在你的测试中添加 @Import(TestConfiguration.class)

这样,如果有额外的实现,你只需要将它添加到 TestConfiguration 中。

唯一需要注意的是,通过使用 @Qualifier 注解来添加适当的接口实现。

英文:

Add a TestConfiguration and declare all the beans implementing the interface in the configuration. Then add an @Import(TestConfiguration.class) in your tests.

That way if there is an extra implementation you only add it in the TestConfiguration.

Only thing you need to take care of is adding the appropriate implementation of the interface with use of the @Qualifier annotation.

huangapple
  • 本文由 发表于 2020年9月1日 01:29:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63675483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定