版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/82798221
使用静态工厂是实例化Bean的另一种实例化方式。该方式要求开发者创建一个静态发工厂的方法来创建Bean的实例,其Bean配置中的class属性所指定的不再是Bean实例的实现类,而是静态工厂类,同时还需要使用factory-method属性来指定所创建的静态工厂方法。下面通过一个例子来演示如何使用静态工厂方式实例化Bean
1、在chapter02项目的src目录下,创建一个com.itheima.instance.static_factory包,在该包中创建一个Bean2类,该类和Bean1一样不需要添加任何方法
package com.itheima.instance.static_factory;
public class Bean2 {
}
2、在com.itheima.instance.static_factory包中,创建一个MyBean2Factory类,并在该类中创建一个静态方法createBean()方法来返回Bean2实例,如下面代码所示:
package com.itheima.instance.static_factory;
public class MyBeanFactory {
public static Bean2 createBean() {
return new Bean2();
}
}
3、在com.itheima.instance.static_factory包中,创建Spring配置文件beans2.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-4.3.xsd">
<bean id="bean2" class="com.itheima.instance.static_factory.MyBeanFactory" factory-method="createBean" />
</beans>
4、在com.itheima.instance.static_factory包中,创建一个测试类InstanceTest2,来测试使用静态工厂方式是否能够实例化Bean,编辑后代码如下:
package com.itheima.instance.static_factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InstanceTest2 {
private static ApplicationContext beanlizi;
public static void main(String[] args) {
String xmlPath = "com/itheima/instance/static_factory/beans2.xml";
beanlizi = new ClassPathXmlApplicationContext(xmlPath);
System.out.println(beanlizi.getBean("bean2"));
}
}
5、执行程序后我们可以看到输出结果如下图所示,表明使用自定义的静态工厂方法,已成功实例化了Bean2