How to select a runtime class based on a Requestparam using Spring MVC?

Asked

Viewed 81 times

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 ApplicationContextand recover the implementation using some variation of getBean? And what are you trying to do by returning this Interface as a result?

  • @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 pattern Strategy for that. In case I use the ApplicationContext, I’ll be simply implementing a Factory in the methods getBean, No? My question was whether it would be possible to do this without implementing the Factory implicitly somewhere.

  • I thought of something simpler: Let’s say you have the interface Tradutor with a method traduzir. Additionally you have the implementations TradutorPtBR, TradutorEnUS, etc like Spring Beans. You would simply use the method getBean to retrieve the correct bean (e.g., by name composing "tradutor" + lingua). The ApplicationContext 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.

  • @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.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.