package com.yiibai.common;
public class Customer
{
private Person person;
public Customer(Person person) {
this.person = person;
}
public void setPerson(Person person) {
this.person = person;
}
@Override
public String toString() {
return "Customer [person=" + person + "]";
}
}
package com.yiibai.common;
public class Person
{
private String name;
private String address;
private int age;
//getter and setter methods
@Override
public String toString() {
return "Person [address=" + address + ",
age=" + age + ", name=" + name + "]";
}
}
<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-2.5.xsd"> <bean id="CustomerBean" class="com.yiibai.common.Customer"> <property name="person" ref="PersonBean" /> </bean> <bean id="PersonBean" class="com.yiibai.common.Person"> <property name="name" value="yiibai" /> <property name="address" value="address1" /> <property name="age" value="28" /> </bean> </beans>
<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-2.5.xsd"> <bean id="CustomerBean" class="com.yiibai.common.Customer"> <property name="person"> <bean class="com.yiibai.common.Person"> <property name="name" value="yiibai" /> <property name="address" value="address1" /> <property name="age" value="28" /> </bean> </property> </bean> </beans>
<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-2.5.xsd"> <bean id="CustomerBean" class="com.yiibai.common.Customer"> <constructor-arg> <bean class="com.yiibai.common.Person"> <property name="name" value="yiibai" /> <property name="address" value="address1" /> <property name="age" value="28" /> </bean> </constructor-arg> </bean> </beans>
执行结果:
package com.yiibai.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
输出结果:
Customer [person=Person [address=address1, age=28, name=yiibai]]
原文:http://www.cnblogs.com/soundcode/p/6367249.html