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!"
    }
相关推荐
Helix25011 分钟前
JDK单元测试实战:JUnit 5与Mockito注解、断言、参数化测试、Mock注入完整指南
java·junit·单元测试·junit 5·mockito·mockmvc·参数化测试
李少兄16 分钟前
Spring Boot 配置占位符与 JNI 原生库容器化适配解析
java·spring boot·后端
Javatutouhouduan42 分钟前
阿里Java面试核心讲(2027最新版)
java·spring boot·mybatis·java面试·后端开发·java程序员·java八股文
简 洁 冬冬1 小时前
深入理解Result与枚举的分工-外壳花名册与协作全链
java·枚举
一起学安全技术1 小时前
Java栈Agent开发 03|Spring AI(二):Tool Calling、MCP 与结构化输出
java·人工智能·spring·spring ai·结构化输出·mcp·tool calling
源码_空间2 小时前
基于Springboot的在线错题本与复习计划系统(源码+文档)
java·spring boot·后端
Rain的Java大神之路2 小时前
别再用“延迟双删”赌一致性:Canal + RocketMQ + Redis 的工业级缓存失效链路,以及 MySQL 分库分表前必须算清的那笔账
java·后端·面试
我命由我123452 小时前
Android Gradle - Android Gradle 配置
android·java·linux·java-ee·kotlin·android studio·android-studio
himobrinehacken2 小时前
HackMyVM靶机Yulian
java·spring boot·后端