6

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.

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Is is somehow better than my current approach ? Because I need to implement another interface in your case ?
It is more in the "Spring way" of doing things. Moreover, if it happens that you add new implementations and reload context at runtime, you won't need to reconfigure anything, because Spring will do it for you.
Ok, I got your point. I just need to implement BeanFactoryAware once, on the class that I'm doing the job, or a separate one, not all implementations. That's very nice, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.