通过工厂模式返回Spring Bean方法解析
工厂返回的可以是一个具体的对象,比如造一辆车,可以返回一个自行车对象,或者汽车对象。
但是在Spring中需要工厂返回一个具体的Service,这就是一个抽象工厂了
一种方法是反射,个人觉得这种方式不好;
还有一种方法是巧妙的使用Map对象,工厂的一个优点就是可扩展,对于这种方式可以说是体现的淋漓尽致了,可以定义多个map,map里也可以扩充
假设现在有一个接口类:BingService
以及实现了这个接口的两个实现类:OneBingServiceImpl,TwoBingServiceImpl
1、在工厂类里定义Map
importjava.util.Map;
publicclassBingServiceFactory{
//Map中的Value是ServiceBean
privateMapserviceMap;
//返回对应的Service
publicBingServicegetBingService(Stringplatform){
returnserviceMap.get(platform);
}
publicMapgetServiceMap(){
returnserviceMap;
}
publicvoidsetServiceMap(MapserviceMap){
this.serviceMap=serviceMap;
}
}
2、是用注解方式,配置工厂,同时使用set注入的方法,给用到工厂的bean来set一下
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importjavax.annotation.Resource;
importjava.util.HashMap;
importjava.util.Map;
@Configuration
publicclassBingConfiguration{
@Resource
privateOneServiceImploneService;
@Resource
privateTwoServiceImpltwoService;
@Resource
privateTestServiceImpltestService;
@Bean
publicBingServiceFactorycreateFactory(){
BingServiceFactoryfactory=newBingServiceFactory();
MapserviceMap=newHashMap<>();
serviceMap.put("One",oneService);
serviceMap.put("Two",twoService);
factory.setServiceMap(serviceMap);
testService.setFactory(factory);
returnfactory;
}
}
@Bean注解如果无效的话,可能得@Bean("xxxxServiceFactory")这样的
3、使用set注入的方方式来获取工厂(当然也可以使用Autowired注解注入)
importorg.springframework.stereotype.Component;
@Component
publicclassTestServiceImpl{
privateBingServiceFactoryfactory;
publicvoidtest(){
BingServiceservice=factory.getBingService("One");
}
publicBingServiceFactorygetFactory(){
returnfactory;
}
publicvoidsetFactory(BingServiceFactoryfactory){
this.factory=factory;
}
}
这个工厂可以优化的,不要Factory这个类,直接使用Map就行
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。