静态工厂实例化要求开发者创建一个静态工厂的方法来创建Bean的实例,其Bean配置中的class属性不再是Bean实例的实现类,而是静态工厂类,同时还需要使用factory-method属性来指定所创建的静态工厂方法。
一、在src目录下创建com.itheima.instance.static_factory包,并创建一个Bean类,不做任何处理,导包
二、在该包下创建一个MyBean2Factory类,并在该类中创建一个静态方法来返回Bean2 的实例
package com.itheima.instance.static_factory;
public class MyBean2Factory {
//使用自己的工厂创建Bean2实例
public static Bean2 createBean() {
return new Bean2();
}
}
三、在该包中创建Spring配置文件bean2.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="bean2"
class="com.itheima.instance.static_factory.MyBean2Factory"
factory-method="createBean"/>
</beans>
四、在该包下创建测试类
package com.itheima.instance.static_factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InstanceTest2 {
public static void main(String[] args) {
//定义配置文件路径
String xmlPath = "com/itheima/instance/static_factory/beans2.xml";
//ApplicationContext在加载配置文件时,对Bean进行实例化
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
Bean2 bean = (Bean2) applicationContext.getBean("bean2");
System.out.println(bean);
}
}
运行结果: