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

2025-05-29 0 61

工厂返回的可以是一个具体的对象,比如造一辆车,可以返回一个自行车对象,或者汽车对象。

但是在Spring 中需要工厂返回一个具体的Service,这就是一个抽象工厂了

一种方法是反射,个人觉得这种方式不好;

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

假设现在有一个接口类:BingService

以及实现了这个接口的两个实现类: OneBingServiceImpl,TwoBingServiceImpl

1、在工厂类里定义Map

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
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一下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30
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 注解注入)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
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 就行

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.cnblogs.com/acm-bingzi/p/spring_factory.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 通过工厂模式返回Spring Bean方法解析 https://www.kuaiidc.com/116855.html

相关文章

发表评论
暂无评论