bean文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="teacher" class="com.ppmoney.test.Teacher">
<property name="name" value="Yang"/>
</bean>
<bean id="score" class="com.ppmoney.test.Score">
<constructor-arg name="name" value="数学课"/>
<constructor-arg name="id" value="1"/>
</bean>
<bean id="teacher2" class="com.ppmoney.test.Teacher">
<constructor-arg name="name" value="Zhang"/>
<constructor-arg name="score" ref="score"/>
</bean> </beans>

2.类文件如下

class Teacher extends  Observable
{
public Teacher()
{ }
public Teacher(Score score,String name)
{
this.score=score;
this.name=name;
}
private String name;
private Score score;
public void startLesson()
{
System.out.println(String.format("%s老师%s 开始上课",getScore(),name));
super.setChanged();
super.notifyObservers();
} public String getName() {
return name;
}
public Score getScore() {
return score;
}
public void setName(String name) {
this.name = name;
}
} class Score
{
private String name;
private int id; Score(String name, int id) {
this.name = name;
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} @Override
public String toString()
{
return name;
}
}

3.调用代码如下

ApplicationContext ctx = new ClassPathXmlApplicationContext("bean1.xml");//读取bean.xml中的内容

        Teacher sir=ctx.getBean("teacher2",Teacher.class);
if(sir==null)
{
System.out.println( "Teacher Init Failed..." );
}
else {
System.out.println( "Teacher Init Succ..." );
}
05-22 15:59