知识点介绍:
实例工厂的意思是获取对象实例的方法不是静态的,所以你需要首先new工厂类,再调用普通的实例方法。
【转载使用,请注明出处:http://blog.csdn.net/mahoking】
操作步骤:
1、创建Speaker对象。
public class Speaker {
//使用实例工厂方法实例化Bean
private String speakerName;
public Speaker(String speakerName) {
this.speakerName = speakerName;
}
/**
* 演讲
*/
public void speech() {
System.out.println(toString());
}
@Override
public String toString() {
return "Speaker [speakerName=" + speakerName + "]";
}
}
2、创建SpeakerFactory对象。
public class SpeakerFactory {
/**
* 工厂方法
* @param speakerName
* @return
*/
public Speaker newInstance() {
String speakerName = "Lucy And Lily";
return new Speaker(speakerName);
}
}
3、创建Spring配置文件beanLearn04.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 04 使用实例工厂方法实例化Bean -->
<!-- 定义实例工厂Bean -->
<bean id="speakerFactory" class="com.mahaochen.spring.learn04.SpeakerFactory" />
<!-- 使用实例工厂Bean创建Bean -->
<bean id="speaker04" class="com.mahaochen.spring.learn04.Speaker"
factory-bean="speakerFactory" factory-method="newInstance" >
</bean>
</beans>
4、将Spring配置文件beanLearn04.xml引入到主配置文件beans.xml中。
<!-- Learn 04 使用实例工厂方式实例化Bean -->
<import resource="com/mahaochen/spring/learn04/beanLearn04.xml"/>
5、 编写测试类TestSpring04.java。
public class TestSpring04 {
public static void main(String[] args) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("beans.xml");
//使用实例工厂方法实例化Bean
Speaker speaker04 = beanFactory.getBean("speaker04", Speaker.class);
speaker04.speech();
}
}
【转载使用,请注明出处:http://blog.csdn.net/mahoking】