XML使用有意义的标记来描述数据。
XML文件是由一个个称为元素的部件构成的。只要满足XML标记的命名规则,我们便可以自由地定义一系列独具匠心的标记。
在MyEclipse中新建一个Java project。
右键项目添加Spring支持
project中共有三个类
Me有两个属性Height 、 Weight。
Height有两个属性m、cm。
Weight有一个属性weight。
Me.java
package chenkeyu;
public class Me {
private Height height;
private Weight weight;
// get/set方法
public Height getHeight() {
return height;
}
public void setHeight(Height height) {
this.height = height;
}
public Weight getWeight() {
return weight;
}
public void setWeight(Weight weight) {
this.weight = weight;
}
public String toString(){
return "身高:"+height+"\n"+"体重:"+weight;
}
}
Height.java
package chenkeyu;
public class Height {
private String m;
private String cm;
// get/set方法
public String getM() {
return m;
}
public void setM(String m) {
this.m = m;
}
public String getCm() {
return cm;
}
public void setCm(String cm) {
this.cm = cm;
}
public String toString(){
return m+"米"+cm;
}
}
Weight.java
package chenkeyu;
public class Weight {
private String weight="65";
// get/set方法
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String toString(){
return weight+"公斤";
}
}
测试类
Test.java
package chenkeyu;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test{
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Me me = (Me) ctx.getBean("me");
System.out.println(me);
}
}
applicationContext.xml
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="height" class="chenkeyu.Height">
<property name="m" value="一"></property>
<property name="cm" value="七六"></property>
</bean>
<bean id="weight" class="chenkeyu.Weight">
<property name="weight" value="65"></property>
</bean>
<bean id="me" class="chenkeyu.Me">
<property name="height" ref="height"></property>
<property name="weight" ref="weight"></property>
</bean>
</beans>