实例工厂实例化Bean就是直接创建Bean实例。在XML配置文件中,不使用class属性直接指向bean实例所属的类,而是通过factory-bean属性指向Bean配置的实例化工厂,并且使用factory-method属性指定要调用的实例工厂中的方法。
1 创建类Car(和上文一样)
package com.lq.entities; /** * @Author: Luqing Teacher * @CreateTime: 2024-12-17 * @Description: 汽车类 * @Version: 1.0 */ public class Car { public Car() { System.out.println("这是Car类"); } }
2 创建实例工厂
package com.lq.Factory; import com.lq.entities.Car; /** * @Author: Luqing Teacher * @CreateTime: 2024-12-20 * @Description: 实例工厂 * @Version: 1.0 */ public class MyCarFactory2 { public MyCarFactory2() { System.out.println("工厂实例化中..."); } public Car createCar() { return new Car(); } }
3 配置文件(仔细查看与上文中的不同)
<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="myCarFactory2" class="com.lq.Factory.MyCarFactory2" /> <bean id="car" factory-bean="myCarFactory2" factory-method="createCar" /> </beans>
4 测试类测试
package com.lq.test; import com.lq.entities.Car; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @Author: Luqing Teacher * @CreateTime: 2024-12-20 * @Description: test * @Version: 1.0 */ public class TestCar2 { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-car.xml"); Car car = applicationContext.getBean("car", Car.class); System.out.println(car); } }
结果如下
工厂实例化中... 这是Car类 com.lq.entities.Car 进程已结束,退出代码0