Implement a simple factory pattern with Spring 3 annotations

前端 未结 11 2005
旧巷少年郎
旧巷少年郎 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:26

    You could instantiate "AnnotationConfigApplicationContext" by passing all your service classes as parameters.

    @Component
    public class MyServiceFactory {
    
        private ApplicationContext applicationContext;
    
        public MyServiceFactory() {
            applicationContext = new AnnotationConfigApplicationContext(
                    MyServiceOne.class,
                    MyServiceTwo.class,
                    MyServiceThree.class,
                    MyServiceDefault.class,
                    LocationService.class 
            );
            /* I have added LocationService.class because this component is also autowired */
        }
    
        public MyService getMyService(String service) {
    
            if ("one".equalsIgnoreCase(service)) {
                return applicationContext.getBean(MyServiceOne.class);
            } 
    
            if ("two".equalsIgnoreCase(service)) {
                return applicationContext.getBean(MyServiceTwo.class);
            } 
    
            if ("three".equalsIgnoreCase(service)) {
                return applicationContext.getBean(MyServiceThree.class);
            } 
    
            return applicationContext.getBean(MyServiceDefault.class);
        }
    }
    

提交回复
热议问题