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!"
    }
相关推荐
PFinal社区_南丞7 分钟前
Go语言开发AI智能体:从Function Calling到Agent框架
后端·go
货拉拉技术24 分钟前
货拉拉海豚平台-大模型推理加速工程化实践
人工智能·后端·架构
神奇小汤圆37 分钟前
请不要自己写,Spring Boot非常实用的内置功能
后端
神奇小汤圆1 小时前
突破Netty极限:基于Java 21 FFM API手写高性能网络通信框架
后端
Java编程爱好者1 小时前
给 Spring Boot 接口加了幂等保护:Token 机制 + 结果缓存,一个注解搞定
后端
Java编程爱好者1 小时前
字节二面:Redis 能做消息队列吗?怎么实现?
后端
爱找乐子的李寻欢1 小时前
防止字符串 ID 隐式转换导致的数据越权漏洞
后端
JavaGuide1 小时前
字节二面:Redis 能做消息队列吗?怎么实现?
redis·后端
暮色妖娆丶3 小时前
不过是吃了几年互联网红利罢了,我高估了自己
java·后端·面试