SpringBoot工厂模式

前言

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

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

一、建立父类

java 复制代码
public abstract class Animal {
    public abstract void makeSound();
    public abstract String getType();
}

二、两个子类

java 复制代码
@Component
public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Miao!");
    }

    @Override
    public String getType() {
        return "cat";
    }
}
java 复制代码
@Component
public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Wang!");
    }

    @Override
    public String getType() {
        return "dog";
    }
}

三、工厂类注入到 map 里

java 复制代码
@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;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Animal> beansOfType = this.appContext.getBeansOfType(Animal.class);
        beansOfType.values().forEach(animal -> animalMap.put(animal.getType(), animal));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.appContext = applicationContext;
    }
}

四、测试

java 复制代码
	@Autowired
    private 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!"
    }
相关推荐
aiotto资源分享14 分钟前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
利威尔xu25 分钟前
Go Mutex 饥饿模式:正常模式等待者饿死,1ms 阈值自动切换崩溃
开发语言·后端·面试·golang·并发编程
一条Go34 分钟前
边缘 Agent:为什么是它连出来,而不是平台连进去
后端·架构·github
RuoyiOffice1 小时前
SpringBoot3+Vue3 采购到付款:ERP、WMS与财务如何按同一来源协同
java·spring boot·架构·vue
huangfuyk1 小时前
前端融入/转后端避坑指南:AI 时代的安全边界、数据防线与实战细节
后端·ai编程
文丑颜不良啊1 小时前
LeetCode3261~3280题目解析
java·leetcode
代码不停1 小时前
Spring 原理
java·spring
掘金者阿豪1 小时前
GitLab 服务器疑似遭入侵:从 502 故障到 Root 权限异常的完整排查复盘
后端
企业数字化笔记2 小时前
报表上线怎么对账?口径回归、权限抽检与差异定位
java·spring boot·mysql
乌暮2 小时前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis