Search code examples
javaspringdependency-injectioninversion-of-control

Loading different stateless Spring beans per request


I am trying to find out what's the best way to use Spring (or not) for loading beans on demand. Here's an example. Let's say that there are two types of mechanic beans

@Bean("japanese-mechanic")
public Mechanic japaneseMechanic(){
  return new JapaneseMechanicImpl
}

@Bean("german-mechanic")
public Mechanic germanMechanic(){
  return new GermanMechanicImpl
}

My question is how do I load the right bean per request. Currently, the way we do it is using "Context.getBean", so it would look something like

String beanName = request.getParameter("typeOfCar") + "-mechanic";
Mechanic mechanic = Context.getBean(beanName,Mechanic.class);

I understand that calling "Context.getBean" this way violates IOC, so looking for a better way to do this, if available. Can someone suggest some alternatives to doing this? Thanks!


Solution

  • You could avoid accessing the context directly by wiring all the mechanics to your own map like the following:

    @Autowired
    Map<String, Mechanic> mechanics;
    
    Mechanic mechanic = mechanics.get(beanName);
    

    So instead of fetching the bean from the context map, you autowire them to your own map and fetch them from there. Could be considered better style, or if you have requirements that you can't access the context directly.