通过工厂模式返回Spring Bean方法解析
作者:贾树丙
这篇文章主要介绍了通过工厂模式返回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 就行
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
