知识点介绍:
静态工厂顾名思义,就是通过调用静态工厂的方法来获取自己需要的对象,为了让spring管理所有对象,我们不能直接通过"工程类.静态方法()"来获取对象,而是依然通过spring注入的形式获取。
【转载使用,请注明出处:http://blog.csdn.net/mahoking】
操作步骤:
1、创建Speaker对象。
/**
* 静态工厂类
*
*/
public class Speaker {
private String name ;
private String topic;
private int timeHour;
private static Speaker speaker = null;
private Speaker() {
this.name = "Jacke";
this.topic = "play football!";
this.timeHour = 2;
}
/**
* 工厂方法
* @return
*/
public static Speaker getInstance() {
if(null==speaker){
speaker = new Speaker();
}
return speaker;
}
/**
* 演讲
*/
public void speech() {
System.out.println(toString());
}
@Override
public String toString() {
return "Speaker [name=" + name + ", topic=" + topic + ", timeHour="
+ timeHour + "]";
}
}
2、创建Spring配置文件beanLearn03.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">
<!-- Learn 03使用静态工厂方式实例化Bean -->
<!--使用有参数构造参数-->
<bean id="speaker03" class="com.mahaochen.spring.learn03.Speaker" factory-method="getInstance">
</bean>
</beans>
3、将Spring配置文件beanLearn03.xml引入到主配置文件beans.xml中。
<!-- Learn 03 使用静态工厂方式实例化Bean -->
<import resource="com/mahaochen/spring/learn03/beanLearn03.xml"/>
4、编写测试类TestSpring03.java。
public class TestSpring03 {
public static void main(String[] args) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("beans.xml");
//使用静态工厂方式实例化Bean
Speaker speaker03 = beanFactory.getBean("speaker03", Speaker.class);
speaker03.speech();
}
}
【转载使用,请注明出处:http://blog.csdn.net/mahoking】