1.新建实体类
public class Person { private String name; private String age; private Car car; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", car=" + car + "]"; } }
2.新建XML文件
<?xml version="1.0" encoding="UTF-8"?> <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.1.xsd"> <bean id="car" class="com.auguigu.spring.beans.Car"> <constructor-arg value="Audi" type="java.lang.String"></constructor-arg> <constructor-arg value="Shanghai" type="java.lang.String"></constructor-arg> <constructor-arg value="30000" type="int"></constructor-arg> </bean> <bean id="person" class="com.auguigu.spring.beans.Person"> <property name="name" value="Tom"></property> <property name="age" value="23"></property> <property name="car" ref="car"></property> </bean> </beans>
这里通过ref来引入car这个bean
3.测试类Main
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("./applicationContext.xml"); Person p = (Person) ctx.getBean("person"); System.out.println(p); } }
总结:
可以使用property属性的ref建立bean之间的引用关系