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浅拷贝和深拷贝理解笔记
java·linux·开发语言·笔记·python·学习
码不停蹄的玄黓几秒前
线上频繁FullGC完整排查流程
java
兔老大RabbitMQ几秒前
IDEA 打字打在光标右边 / 删除异常问题
java·ide·intellij-idea
jeffer_liu3 分钟前
Spring AI 生产级实战:多模态
java·人工智能·后端·spring·大模型
码不停蹄的玄黓5 分钟前
Arthas 最常用命令速查表
java
石榴树下的七彩鱼8 分钟前
发票OCR识别API接入教程:从图像到结构化数据的完整实战(附Python/Java/PHP/JS代码)
java·python·ocr·api接口·财务自动化·石榴智能·发票ocr
Gopher_HBo8 分钟前
Go语言学习笔记(五)异常处理
后端
爱吃羊的老虎8 分钟前
【JAVA】Java微服务—分布式事务框架Seata
java·开发语言
Jul1en_13 分钟前
【Redis】事务详解、WATCH 实现思想
java·spring boot·redis·mysql·java-ee
SimonKing16 分钟前
你还在靠重启来调线程池?别人已经做到了实时调控,3分钟接入
java·后端·程序员