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!"
    }
相关推荐
Java编程爱好者8 分钟前
面试官:你知道 MCP、Skill、Function Call 这三个的区别吗?
后端
狂炫冰美式11 分钟前
把手从键盘上抬起来:AI 编程的 3 个不可逆阶段
前端·后端·ai编程
王中阳Go1 小时前
Go 协程池满了怎么办?面试官问我“兜底策略”,我差点挂了……
后端
蝎子莱莱爱打怪2 小时前
Centos7中一键安装K8s集群以及Rancher安装记录
运维·后端·kubernetes
茶杯梦轩2 小时前
CompletableFuture 在 项目实战 中 创建异步任务 的核心优势及使用场景
服务器·后端·面试
埃博拉酱3 小时前
SMB服务器无法访问?一次PowerShell故障排查演练
后端
大道至简Edward3 小时前
Spring Boot 2.7 + JDK 8 升级到 Spring Boot 3.x + JDK 17 完整指南
spring boot·后端
透明人_x3 小时前
OpenClaw安装
人工智能·后端
程序员清风3 小时前
用了三年AI,我总结出高效使用AI的3个习惯!
java·后端·面试
用户8356290780513 小时前
自动化文档处理:Python 批量提取 PDF 图片
后端·python