当前位置: 首页 > news >正文

Spring中的工厂模式详解及应用示例

1. Spring中的BeanFactory

BeanFactory是一个接口,表示它是一个工厂,负责生产和管理bean。在Spring中,BeanFactory是IOC容器的核心接口,定义了管理Bean的通用方法,如 getBeancontainsBean

BeanFactory与IOC容器

在这里插入图片描述

DefaultListableBeanFactory类图

在这里插入图片描述

BeanFactory只是个接口,并不是IOC容器的具体实现。Spring提供了多种实现,如 DefaultListableBeanFactoryXmlBeanFactoryApplicationContext等。

ApplicationContext

ApplicationContext是Spring框架中最常用的IoC容器,是BeanFactory的子接口,提供了更丰富的功能和更强的扩展性。

在这里插入图片描述

ApplicationContext的子类

  1. ClassPathXmlApplicationContext:基于XML配置文件的ApplicationContext实现类,可以加载类路径下的XML配置文件。
  2. FileSystemXmlApplicationContext:基于XML配置文件的ApplicationContext实现类,可以加载文件系统中的XML配置文件。
  3. AnnotationConfigApplicationContext:基于Java注解的ApplicationContext实现类,可以通过Java配置类来管理Bean实例。
  4. WebApplicationContext:适用于Web应用场景的ApplicationContext子接口,提供了更丰富的Web应用支持。

这些ApplicationContext子类都实现了ApplicationContext接口,提供了不同的功能和扩展性,可以根据具体的应用场景选择合适的ApplicationContext子类来管理Bean实例。

BeanFactory的使用示例

// User.java
public class User {private int id;private String name;private Friends friends;public User() { }public User(Friends friends) {this.friends = friends;}// getters and setters...
}// Friends.java
public class Friends {private List<String> names;public Friends() { }public List<String> getNames() {return names;}public void setNames(List<String> names) {this.names = names;}
}

配置文件(bean.xml)

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.2.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.2.xsdhttp://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-4.2.xsd"><bean id="User" class="com.example.factory.User"><property name="friends" ref="UserFriends" /></bean><bean id="UserFriends" class="com.example.factory.Friends"><property name="names"><list><value>LiLi</value><value>LuLu</value></list></property></bean>
</beans>

测试类

public class SpringFactoryTest {public static void main(String[] args) {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");User user = ctx.getBean("User", User.class);List<String> names = user.getFriends().getNames();for (String name : names) {System.out.println("FriendName: " + name);}ctx.close();}
}

2. Spring中的FactoryBean

FactoryBean 是一个工厂Bean,相当于将工厂类放到了Spring中管理。当获取此Bean时返回的是该工厂生成的Bean。

FactoryBean通常用于创建比较复杂的bean。对于一般的bean,可以直接用XML配置;但如果一个bean的创建过程中涉及到很多其他bean和复杂的逻辑,用XML配置可能比较困难,这时可以考虑用FactoryBean。

FactoryBean接口

public interface FactoryBean<T> {String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";@NullableT getObject() throws Exception;@NullableClass<?> getObjectType();default boolean isSingleton() {return true;}
}

代码示例

Car实体

public class Car {private String color;private String brand;private double price;// getters and setters...
}

CarFactoryBean

@Component("carFactoryBean")
public class CarFactoryBean implements FactoryBean<Car> {@Overridepublic Car getObject() throws Exception {System.out.println("FactoryBean的getObject替换掉getBean...");return new Car();}@Overridepublic Class<?> getObjectType() {return Car.class;}@Overridepublic boolean isSingleton() {return true;}
}

测试类

public class Test01 {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);Car car = context.getBean(Car.class);System.out.println(car);}
}// 打印结果
// FactoryBean的getObject替换掉getBean...
// com.example.Car@4d14b6c2

在实例化Bean过程比较复杂的情况下,如果按照传统的方式,则需要在中提供大量的配置信息。配置方式的灵活性是受限的,这时采用编码的方式可能会得到一个简单的方案。Spring为此提供了一个 FactoryBean的工厂类接口,用户可以通过实现该接口定制实例化Bean的逻辑。

FactoryBean 与 BeanFactory 的区别

  • BeanFactory是一个大工厂,是IOC容器的根基,有繁琐的bean声明周期处理过程,可以生成各种各样的Bean。
    在这里插入图片描述

  • FactoryBean是一个小工厂,它自己本身也是一个Bean,但是可以生成其他Bean。用户可以通过实现该接口定制实例化Bean的逻辑。
    在这里插入图片描述

这种设计模式本质上是一个工厂方法模式,通过公共的工厂接口和不同的具体工厂,来获取对象。

http://www.lryc.cn/news/396710.html

相关文章:

  • Electron 简单搭建项目
  • 旗晟智能巡检机器人:开启工业运维的智能化新篇章
  • vue3的常用 Composition API有哪些?
  • 深度优先算法-DFS(算法篇)
  • C++模块化之内部类
  • k8s-第九节-命名空间
  • 【AI大模型新型智算中心技术体系深度分析 2024】
  • 王道计算机数据结构+插入排序、冒泡排序、希尔排序、快速排序、简单选择排序
  • python爬虫学习(三十三天)---多线程上篇
  • JavaScript 原型链那些事
  • nginx的知识面试易考点
  • 每日Attention学习9——Efficient Channel Attention
  • Java语言程序设计——篇三(1)
  • 基于SpringBoot实现轻量级的动态定时任务调度
  • 夸克升级“超级搜索框” 推出AI搜索为中心的一站式AI服务
  • element-ui el-select选择器组件下拉框增加自定义按钮
  • Python基于you-get下载网页上的视频
  • 大模型/NLP/算法面试题总结3——BERT和T5的区别?
  • vue3项目打包的时候,怎么区别测试环境,和本地环境
  • 小特性 大用途 —— YashanDB JDBC驱动的这些特性你都get了吗?
  • 全网最全的软件测试面试八股文
  • VMware虚拟机配置桥接网络
  • 华为机考真题 -- 攀登者1
  • 深入理解Python密码学:使用PyCrypto库进行加密和解密
  • MMSegmentation笔记
  • Python基础语法:变量和数据类型详解(整数、浮点数、字符串、布尔值)①
  • 【C++航海王:追寻罗杰的编程之路】关联式容器的底层结构——红黑树
  • MySQL DDL
  • 从模型到应用:李彦宏解读AI时代的新趋势与挑战
  • C++ STL 随机数用法介绍