码迷,mamicode.com
首页 > 编程语言 > 详细

spring注入成员对象

时间:2014-09-29 22:54:11      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   使用   ar   java   文件   sp   2014   

就是将对象注入到另外一个对象中。这个例子就是有一个学校类,学校类中有一个校长类,最后使用测试文件输出学校类中的信息。

代码结构

bubuko.com,布布扣


学校类

package com.test.SpringGetSet;

public class School {
	private Present present;
	
	public Present getPresent() {
		return present;
	}

	public void setPresent(Present present) {
		this.present = present;
	}

	public String getShoolName() {
		return shoolName;
	}

	public void setShoolName(String shoolName) {
		this.shoolName = shoolName;
	}

	String shoolName;
	
	public void say()
	{
		System.out.println("校名:"+shoolName);
		System.out.println("校长姓名:"+present.getName());
	}

}

校长类

package com.test.SpringGetSet;

public class Present {
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	private int age;

}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="present" class="com.test.SpringGetSet.Present">
        <property name="name" value="杨发癫" />
        <property name="age" value="40" />
    </bean>
    <bean id="school" class="com.test.SpringGetSet.School">
        <property name="shoolName" value="上饶县中" />
        <property name="present">
            <ref bean="present"/>
        </property>
    </bean>
</beans>


测试类

package com.test.SpringGetSet;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import SpringByHand.Hello;

public class SetDemo001 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BeanFactory factory=new XmlBeanFactory(new ClassPathResource("com/test/SpringGetSet/beans.xml"));
		School s=(School) factory.getBean("school");
		s.say();
	}

}


输出结果

bubuko.com,布布扣


spring注入成员对象

标签:blog   http   io   使用   ar   java   文件   sp   2014   

原文地址:http://blog.csdn.net/itbuluoge/article/details/39675113

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!