英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论