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!"
    }
相关推荐
uhakadotcom2 小时前
RunPod:AI云计算的强大助手
后端·面试·github
Pitayafruit2 小时前
📌 Java 工程师进阶必备:Spring Boot 3 + Netty 构建高并发即时通讯服务
spring boot·后端·netty
uhakadotcom2 小时前
Google AlloyDB AI 与 PostgreSQL 的核心区别
后端·面试·github
uhakadotcom2 小时前
使用Go语言编写简单爬虫程序
后端·面试·github
梦想实现家_Z2 小时前
SpringBoot实现MCP Server实战详解
spring boot·后端·mcp
你是理想3 小时前
wait 和notify ,notifyAll,sleep
java·开发语言·jvm
helloworld工程师3 小时前
【微服务】SpringBoot整合LangChain4j 操作AI大模型实战详解
java·eclipse·tomcat·maven
Java&Develop3 小时前
idea里面不能运行 node 命令 cmd 里面可以运行咋回事啊
java·ide·intellij-idea
q567315233 小时前
使用Java的HttpClient实现文件下载器
java·开发语言·爬虫·scrapy
bobz9654 小时前
qemu 对于外部网卡的配置方式
后端