I am implementing a service locator pattern in Spring using the ServiceLocatorFactoryBean as described here: https://springframework.guru/service-locator-pattern-in-spring/
I have multiple Parser implementations and want to select the correct one at runtime to handle the request. Each Parser implements the parse(String) method.
@Autowired
private ParserFactory parserFactory;
@PostMapping("/parse/{format}")
public String parse(@PathVariable String format, @RequestBody String content) {
return parserFactory.getParser(format).parse(content);
}
@Bean("parserFactory")
public FactoryBean serviceLocatorFactoryBean() {
ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean();
factoryBean.setServiceLocatorInterface(ParserFactory.class);
return factoryBean;
}
(Note that is a very simplistic example. Security, service, error handling, etc. omitted).
This works, but the ServiceLocatorFactoryBean documentation says this:
Such service locators permit the decoupling of calling code from the BeanFactory API, by using an appropriate custom locator interface. They will typically be used for prototype beans, i.e. for factory methods that are supposed to return a new instance for each call. The client receives a reference to the service locator via setter or constructor injection, to be able to invoke the locator's factory methods on demand. For singleton beans, direct setter or constructor injection of the target bean is preferable.
How does that bolded part relate to my use case? My services are all singletons and setter or construction injection is not an option as I won't know the requested parser type until the request comes into the controller.