Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Multiple Implementation of same interface

Tags:

java

spring

I have an Interface and multiple implementation classes, around 10, of this interface.

I have a naming convention like prefix + name + suffix so during runtime, I can add @Autowired private Map<String, MyInterface> myImplementations; and then access the implementation class with myImplementations.get() method.

Is there a better way of accessing those implementations? I only know which impl. I needed during runtime, changes depends on the message I received.

like image 980
Gokhan Oner Avatar asked Jul 14 '15 08:07

Gokhan Oner


1 Answers

You can implement BeanFactoryAware interface in your class and then use injected bean factory to get needed implementation:

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

or

Interface impl = beanFactory.getBean(InterfaceImpl.class);
like image 126
Mikhail Avatar answered Oct 22 '22 18:10

Mikhail