1
Let’s say I have the following @Restcontroller in my code that uses Spring MVC:
@RestController
public class Exemplo {
@RequestMapping(value = "exemplo", method = RequestMethod.GET)
public InterfaceDeExemplo exemplo(@RequestParam String escolha) {
Interface resultado;
/* Cria uma instância por aqui. */
return resultado;
}
}
And let’s say I have some implementations of mine Interfacedeexample, Implementacaoa, Implementacaob and Implementacaoc available at runtime and that I have to choose between them from the @Requestparam String choice.
I know it would be possible to choose using Factory design standards, but I’m looking for a way to do this using dependency injection.
I found that maybe the solution to this problem was related to Spring’s @Conditional annotation, but I don’t know how I would get the value of @Requestparam String choice in my class implementing the interface Condition.
Hi Gabriel, maybe I’m oversimplifying the problem, but it wouldn’t be enough for you to inject the
ApplicationContext
and recover the implementation using some variation ofgetBean
? And what are you trying to do by returning thisInterface
as a result?– Anthony Accioly
@Anthonyaccioly the return simply turns a
JSON
and is sent to the customer. The parameter I called choice there is actually the language, because in each language I will use a different algorithm to perform the translation (because of this I cannot simply translate the project’s strings). I tried to follow the design patternStrategy
for that. In case I use theApplicationContext
, I’ll be simply implementing aFactory
in the methodsgetBean
, No? My question was whether it would be possible to do this without implementing theFactory
implicitly somewhere.– Gabriel Rossini Martins
I thought of something simpler: Let’s say you have the interface
Tradutor
with a methodtraduzir
. Additionally you have the implementationsTradutorPtBR
,TradutorEnUS
, etc like Spring Beans. You would simply use the methodgetBean
to retrieve the correct bean (e.g., by name composing"tradutor" + lingua
). TheApplicationContext
is, among other things, a Factory bean. But in case you do not explicitly implement any standard, you are only using what Spring gives you.– Anthony Accioly
@Anthonyaccioly understood. I had solved the problem here in a similar way, but using Reflection. I will try to use your approach that seems less conducive to error.
– Gabriel Rossini Martins