在 Spring 中一共有两种类型的 bean
- 普通bean:在配置文件中定义的 bean 类型就是返回对象的类型
- 工厂bean:在配置文件中定义 bean 类型可以和返回对象的类型不一样
如何创建工厂bean
创建工厂类,实现接口FactoryBean
假设我们现在需要一个 Student 的工厂类
实现接口中的方法
注意Factory接口的泛型里面就是我们工厂类所创建出来的对象的类型
配置xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="factory1" class="com.ctguyxr.spring5.factorybean.StudentFactoryBean" /></beans>
测试
注意getBean的时候要填上Student.class
