Spring自定义对象的注入配置

         以上文章介绍的方法或方式,都是注入基本数据类型例如String,int等等,本例将介绍自定义对象的注入方式的配置。
【转载使用,请注明出处:http://blog.csdn.net/mahoking

操作步骤:
1、 创建Topic对象。

public class Topic {

	/**内容*/
	private String context;

	public String getContext() {
		return context;
	}

	public void setContext(String context) {
		this.context = context;
	}

	public Topic(String context) {
		this.context = context;
	}
}

2、 创建Speaker对象。

public class Speaker {

	private Topic topic;

	public Topic getTopic() {
		return topic;
	}

	public void setTopic(Topic topic) {
		this.topic = topic;
	}
	
	/**
	 * 演讲
	 */
	public void speech() {
		System.out.println("[Speaker's Topic Context is ]"+topic.getContext()+".");
	}
}

3、 创建Spring配置文件middleLearn01.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 middle 01    使用内部bean,但该bean不能被其他bean使用
	<bean id="speaker05" class="com.mahaochen.spring.middle.learn05.Speaker"
		scope="singleton">
		<property name="topic">
			<bean class="com.mahaochen.spring.middle.learn05.Topic">
				<constructor-arg index="0" value="Tour and Recollection" />
			</bean>
		</property>
	</bean> -->
	<!--  OR Learn middel 02 -->
	<bean id="middleSpeaker01" class="com.mahaochen.spring.middle.learn01.Speaker"
		scope="singleton">
		<property name="topic" ref="topic"/>
	</bean>
	<bean id="topic" class="com.mahaochen.spring.middle.learn01.Topic">
		<constructor-arg index="0" value="Tour and Recollection" />
	</bean>
</beans>

4、将Spring配置文件middleLearn01.xml引入到主配置文件beans.xml中。

<import resource="com/mahaochen/spring/middle/learn01/middleLearn01.xml"/>

5、编写测试类TestSpringMiddle01.java。

public class TestSpringMiddle01 {

	public static void main(String[] args) {
		BeanFactory beanFactory = new ClassPathXmlApplicationContext("beans.xml");
		Speaker speaker05 = beanFactory.getBean("middleSpeaker01", Speaker.class);
		speaker05.speech();
	}
}

【转载使用,请注明出处:http://blog.csdn.net/mahoking




 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。