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!"
    }
相关推荐
snow@li3 分钟前
Java:事务管理全景梳理/解决业务系统数据一致性问题
java
额额额对了9 分钟前
Linux 进程管理详解:从概念到实战
java·服务器·前端
evans在进步10 分钟前
Spring Boot 启动流程与 @SpringBootApplication 核心原理详解
java·spring boot·后端
fatcoder11 分钟前
玩转 Redis · Set 篇
前端·redis·后端
许彰午12 分钟前
11-rawSql占位符替换
java·低代码·架构
摇滚侠20 分钟前
《SpringBoot 3:入门与应用实战》第 6 章 Spring Boot 最佳实践 阅读笔记 12
android·spring boot·笔记
掘金者阿豪26 分钟前
你的公网 IP 是专线还是动态变化的?一文讲透动态 IP 与固定 IP 的那些事
前端·后端
超超不吵吵26 分钟前
Java AI转型实战(八):RAG完整链路实战
后端
码匠许师傅26 分钟前
【C++ 面试真题】聊聊 C++ 的类型特征( type_traits)
java·c++·面试
java1234_小锋28 分钟前
Spring框架的创始人开发了一个Java AI智能体框架
java·人工智能·spring