简体   繁体   English

Spring多个实现相同的接口

[英]Spring Multiple Implementation of same interface

I have an Interface and multiple implementation classes, around 10, of this interface. 我有一个接口和多个实现类,大约10个,这个接口。

I have a naming convention like prefix + name + suffix so during runtime, I can add @Autowired private Map<String, MyInterface> myImplementations; 我有一个命名约定,如prefix + name + suffix所以在运行时,我可以添加@Autowired private Map<String, MyInterface> myImplementations; and then access the implementation class with myImplementations.get() method. 然后使用myImplementations.get()方法访问实现类。

Is there a better way of accessing those implementations? 有没有更好的方法来访问这些实现? I only know which impl. 我只知道哪个impl。 I needed during runtime, changes depends on the message I received. 我需要在运行时,更改取决于我收到的消息。

You can implement BeanFactoryAware interface in your class and then use injected bean factory to get needed implementation: 您可以在类中实现BeanFactoryAware接口,然后使用注入的bean工厂来获得所需的实现:

Interface impl = beanFactory.getBean("interfaceimpl");

or 要么

Interface impl = beanFactory.getBean(InterfaceImpl.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM