package news;
public class Address {
private String city;
private String school;
public Address(String city, String school) {
super();
this.city = city;
this.school = school;
}
public Address() {
this.city = "杭州";
this.school = "浙江大學";
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
package news;
public class Students {
private String name;
private int age;
Address address;
public Students(String name, int age, Address address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public Students() {
super();
// TODO Auto-generated constructor stub
}
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;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
<?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">
<bean name="a1" class="news.Address">
<constructor-arg index="0" type="java.lang.String" value="山東"></constructor-arg>
<constructor-arg index="1" type="java.lang.String" value="山東農業大學"></constructor-arg>
</bean>
<bean name="a2" class="news.Address"></bean>
<bean name="a3" class="news.Address">
<property name="city" value="北京"></property>
<property name="school" value="解放軍大學"></property>
</bean>
<bean name="a4" class="news.Address">
<property name="city" value="北京"></property>
<property name="school" value="解放軍大學"></property>
</bean>
<bean name="s1" class="news.Students">
<property name="name" value="曾傑"></property>
<property name="age" value="21"></property>
<property name="address" ref="a4"></property>
</bean>
</beans>
package news;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class main {
public static void main(String[] args) {
//創建一個容器實例
ApplicationContext act=new ClassPathXmlApplicationContext("news.xml");
Address address1;//帶參數的構造器注入
Address address2;//無參數的構造器注入
Address address3;//先調用無參構造器,再調用getset
Students ss;//先調用無參構造器,再調用getset注入引用屬性
address1=(Address)act.getBean("a1");
System.out.println("城市:"+address1.getCity()+" 學校:"+address1.getSchool());
address2=(Address)act.getBean("a2");
System.out.println("城市:"+address2.getCity()+" 學校:"+address2.getSchool());
address3=(Address)act.getBean("a3");
System.out.println("城市:"+address3.getCity()+" 學校:"+address3.getSchool());
ss=(Students)act.getBean("s1");
System.out.println("姓名:"+ss.getName()+" 年齡:"+ ss.getAge()+" 城市:"+ss.getAddress().getCity()+" 學校:"+ss.getAddress().getSchool());
}
}