当前位置: 首页 > news >正文

SpringBoot工厂模式

前言

下面的示例展示了 SpringBoot 中如何使用工厂模式,该示例通过 ApplicationContext 直接获取 Spring 容器中所有 Animal 的 Bean,然后将它们存储在 animalMap 中,使用时直接从 Map 中获取实例。

另一种工厂模式可参考我另一篇文章 :SpringBoot 工厂模式自动注入到Map

一、建立父类

public abstract class Animal {public abstract void makeSound();public abstract String getType();
}

二、两个子类

@Component
public class Cat extends Animal {@Overridepublic void makeSound() {System.out.println("Miao!");}@Overridepublic String getType() {return "cat";}
}
@Component
public class Dog extends Animal {@Overridepublic void makeSound() {System.out.println("Wang!");}@Overridepublic String getType() {return "dog";}
}

三、工厂类注入到 map 里

@Component
public class AnimalFactory implements ApplicationContextAware, InitializingBean {private final Map<String, Animal> animalMap = new ConcurrentHashMap<>();private ApplicationContext appContext;public Animal getAnimal(String animalType) {Animal animal = this.animalMap.get(animalType);if (animal == null) {throw new IllegalArgumentException("Unsupported animal type: " + animalType);}return animal;}@Overridepublic void afterPropertiesSet() throws Exception {Map<String, Animal> beansOfType = this.appContext.getBeansOfType(Animal.class);beansOfType.values().forEach(animal -> animalMap.put(animal.getType(), animal));}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.appContext = applicationContext;}
}

四、测试

@Autowiredprivate AnimalFactory animalFactory;public void printSound() throws Exception {Animal animal_1 = animalFactory.getAnimal("dog");animal_1.makeSound(); // 输出 "Wang!"Animal animal_2 = animalFactory.getAnimal("cat");animal_2.makeSound(); // 输出 "Miao!"}

http://www.mrgr.cn/news/12659.html

相关文章:

  • python多进程日志以及分布式日志的实现方式
  • C/C++ 汇编基础知识概述
  • Python算法工程师面试整理-算法
  • Vue动态表头数据
  • 索迪迈科技油罐车监控系统中车载摄像头的布局策略
  • 选择个人开发者进行软件开发的潜在风险分析
  • IOS半越狱工具nathanlr越狱教程
  • 金融工程--基础策略构建
  • selenium(一)基于java、元素定位
  • 【大模型论文】大模型如何做音乐?最新89页《音乐基础模型》综述
  • 猫头虎分享:什么是信创体系?
  • 哪些领域最适合采用音视频私有化解决方案?
  • 秋招 8.24京东笔试 JDS-2025届秋招-后端开发工程师-第3批
  • Kafka·概述
  • HTML静态网页成品作业(HTML+CSS+JS)——体育足球介绍设计制作(3个页面)
  • 15:00面试,15:06就出来了,问的问题有点变态。。。
  • Java栈的应用
  • 缓存三剑客(穿透,雪崩,击穿)理解
  • SparkShop开源商城 uploadFile 任意文件上传漏洞复现
  • 内存删除的原理