[英]Spring - Bind an interface to an implementation class programmatically
In Spring DI, we can bind an interface with an instance programmatically as below: 在Spring DI中,我们可以通过编程方式将接口与实例绑定,如下所示:
@Bean
public MyService getMyService() {
return new MyService1();
}
Is there a way to bind the interface with MyService1.class instead? 有没有办法将接口与MyService1.class绑定? I do not want to create the instance myself. 我不想自己创建实例。
You can annotate your MyService1
class with @Service
(or @Component
, @Repository
and others...). 您可以使用@Service
(或@Component
, @Repository
等)来注释MyService1
类。
This way, when you inject a MyService
interface, it will automatically look for existing implementations and find MyService1
. 这样,当您注入MyService
接口时,它将自动查找现有实现并找到MyService1
。
Note that your Spring configuration must contain component scanning or equivalent. 请注意,您的Spring配置必须包含组件扫描或等效扫描。
NB : if you have multiple implementations of your interface, you can use @Qualifier
s. 注意 :如果您的界面有多种实现,则可以使用@Qualifier
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.