Spring 使用实例工厂方法实例化Bean

知识点介绍:
        实例工厂的意思是获取对象实例的方法不是静态的,所以你需要首先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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hoking

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值