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!"
    }
相关推荐
程序媛学姐14 分钟前
Spring Boot的GraalVM支持:构建低资源消耗微服务
spring boot·python·微服务
梁云亮25 分钟前
纯原生Java实现:获取整个项目中指定接口所有的实现类
java·列举接口实现类·获取接口实现类
心海资源41 分钟前
Java多语言DApp质押挖矿盗U源码(前端UniApp纯源码+后端Java)
java·前端·uni-app
催眠大树1 小时前
适配器模式(Adapter Pattern)
java·开发语言·适配器模式
在未来等你1 小时前
互联网大厂Java面试:从Spring到微服务的技术探讨
数据库·spring boot·微服务·java面试·技术栈·互联网大厂
博哥爱学习2 小时前
《Java高级编程:从原理到实战 - 进阶知识篇四》
java·开发语言
-曾牛3 小时前
Java面试:Spring及Spring Cloud技术深度剖析
java·spring·spring cloud·面试·springboot·javaee·面经
冬天的雪20084 小时前
springboot war包tomcat中运行报错,启动过滤器异常,一个或多个筛选器启动失败。
spring boot·tomcat·firefox
啊喜拔牙4 小时前
如何在idea中写spark程序
java·spark·intellij-idea
电商api接口开发4 小时前
ASP.NET MVC 入门与提高指南八
后端·asp.net·mvc