通过工厂模式返回Spring Bean方法解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

通过工厂模式返回Spring Bean方法解析

贾树丙   2020-09-17 我要评论

本文着重讲解了通过工厂模式返回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 就行

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们