Implement a simple factory pattern with Spring 3 annotations

前端 未结 11 2007
旧巷少年郎
旧巷少年郎 2020-12-12 10:37

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

11条回答
  •  再見小時候
    2020-12-12 11:16

    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;
        }
    }
    

提交回复
热议问题