欢迎访问我的个人网站==》 jiashubing.cn

工厂模式如何返回Spring的Bean

  工厂返回的可以是一个具体的对象,比如造一辆车,可以返回一个自行车对象,或者汽车对象。
  但是在Spring 中需要工厂返回一个具体的Service,这就是一个抽象工厂了

  一种方法是反射,个人觉得这种方式不好;
  还有一种方法是巧妙的使用Map对象,工厂的一个优点就是可扩展,对于这种方式可以说是体现的淋漓尽致了,可以定义多个map,map里也可以扩充


  假设现在有一个接口类:BingService
  以及实现了这个接口的两个实现类: OneBingServiceImpl,TwoBingServiceImpl

  1、在工厂类里定义Map

import java.util.Map;

public class BingServiceFactory {

    //Map中的Value是 ServiceBean
    private Map<String, BingService> serviceMap;

    //返回对应的 Service
    public BingService getBingService(String platform) {
        return serviceMap.get(platform);
    }

    public Map<String, BingService> getServiceMap() {
        return serviceMap;
    }

    public void setServiceMap(Map<String, BingService> serviceMap) {
        this.serviceMap = serviceMap;
    }
}

 

  2、是用注解方式,配置工厂,同时使用set 注入的方法,给用到工厂的bean来set一下

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class BingConfiguration {
    @Resource
    private OneServiceImpl oneService;

    @Resource
    private TwoServiceImpl twoService;

    @Resource
    private TestServiceImpl testService;

    @Bean
    public BingServiceFactory createFactory() {
        BingServiceFactory factory = new BingServiceFactory();

        Map<String, BingService> serviceMap = new HashMap<>();
        serviceMap.put("One",oneService);
        serviceMap.put("Two",twoService);
        factory.setServiceMap(serviceMap);

        testService.setFactory(factory);

        return factory;
    }

}

@Bean 注解如果无效的话,可能得 @Bean("xxxxServiceFactory")  这样的

 

  3、使用set 注入的方方式来获取工厂(当然也可以使用Autowired 注解注入)

import org.springframework.stereotype.Component;

@Component
public class TestServiceImpl {

    private BingServiceFactory factory;

    public void test() {
        BingService service = factory.getBingService("One");
    }

    public BingServiceFactory getFactory() {
        return factory;
    }

    public void setFactory(BingServiceFactory factory) {
        this.factory = factory;
    }
}

 

  这个工厂可以优化的,不要Factory 这个类,直接使用Map 就行

 

  原创文章,欢迎转载,转载请注明出处!

posted @ 2019-03-29 14:59  贾树丙  阅读(2519)  评论(0编辑  收藏  举报