S
S
sieur2019-11-15 22:52:42
Java
sieur, 2019-11-15 22:52:42

Spring: how to get one interface implementation from many?

Question on Java Spring. There are several implementations, I want to receive an implementation from the context in the facade class depending on the enum (for example). How to do it correctly in the code of the method? Not in the class field. Need best practice.
Visual illustration (click to enlarge):
5dcf01f5edfd4492441063.png
I see options:
Glue the bean id from this enum, and get the desired bean by id. It can be moved to a separate bean provider class. You will have to follow some agreement, but this is not a big problem.
Somehow truncate the context to the desired package (toyota or bmw), and already search in it by interface. But it seems impossible to cut the context without recreating it, so that's not an option either.
It seems to me that both approaches are not very good. I thought about injecting narrower contexts depending on the enum, but context injection is generally a bad practice, according to Evgeny Borisov.
How to do it competently with Spring? Objects that implement the Cleaner, EngineDiagnost and WheelsChanger interfaces contain fields marked with @Autowired and @Resource, so you cannot create these objects without spring.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bonce, 2019-11-18
@Bonce

Declare the Facade as a bean, and inject the beans you need into it. You can write something like:

@Autowired
Map<String, Car> cars;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question