避免 @Bean 的默认接口实现
假设
- 我有集成测试,因此有一个
ApplicationContextIntegrationTests
类,其中包含虚拟 bean(依赖于其他服务),用于初始化集成配置文件的应用程序上下文,如下所示:
@Bean
public MyService myService(Proc proc) {
return new MyServiceImp();
}
- 我有一个接口
MyInterfaceA< /code> 有 20 个方法(代码是根据 api.yaml 中的定义自动生成的),我无法实现它,也无权访问该实现。该接口(好吧,它是一个实现)也应该插入到应用程序上下文中。显然,我需要实现所有接口方法才能插入该 bean,这会导致 50 行默认方法实现的代码混乱。而且,我需要插入3个接口。
有没有办法避免这么大量的代码?
我发现Lombok提供了一个@Delegate注释,它在类似的情况下使用,但它仅适用于字段,而我需要处理方法(@Bean的bcs) >)。
Let's say
- I have integration tests, therefore there is an
ApplicationContextIntegrationTests
class that contains dummy beans (dependencies on other services) for initializing the app context for integration profile like this:
@Bean
public MyService myService(Proc proc) {
return new MyServiceImp();
}
- I have an interface
MyInterfaceA
with 20 methods (the code is autogenerated based on the definition inapi.yaml
), I cannot implement it and I don't have access to the implementation. This interface (well, it is an implementation) also should be inserted in the application context. Obviously, I need to implement all interface methods in order to insert that bean and it leads to messy code with default methods implementations on 50 lines. Moreover, I need to insert 3 interfaces.
Is there a way to avoid that huge amount of code?
I have found that Lombok provides a @Delegate
annotation which is used in similar situations, but it is appliable only on fields, whereas I need to deal with methods (bcs of @Bean
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个实现 MyInterfaceA 的生成类也是一个 bean 吗?如果是这样,您可以使用
@MockBean
在测试中模拟其实现。这样,无论何时使用MyInterfaceA
类型的 bean,模拟都会被注入到它的位置,并且您可以让模拟执行您想要的任何操作。Is this generated class that implements
MyInterfaceA
also a bean? If so, you can use@MockBean
to mock its implementation in the test. This way, wherever a bean of typeMyInterfaceA
is used, the mock will be injected in its place, and you can have the mock do whatever you want.