I was wondering how I could implement the simple factory pattern with Spring 3 annotations. I saw in the documentation that you can create beans that call the factory class
Following answer of DruidKuma
Litte refactor of his factory with autowired constructor:
@Service
public class MyServiceFactory {
private static final Map myServiceCache = new HashMap<>();
@Autowired
private MyServiceFactory(List services) {
for(MyService service : services) {
myServiceCache.put(service.getType(), service);
}
}
public static MyService getService(String type) {
MyService service = myServiceCache.get(type);
if(service == null) throw new RuntimeException("Unknown service type: " + type);
return service;
}
}