applicationContext.xml配置文件为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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 -->
<bean id="car" class="com.spring.Car">
<constructor-arg value="green"></constructor-arg>
<constructor-arg value="22"></constructor-arg>
</bean>
<bean id="person" class="com.spring.Person">
<property name="name" value="xiao"></property>
<property name="age" value="22"></property>
<property name="car" ref="car"></property>
</bean>
</beans>
package com.spring;
public class Car {
private String name;
private String color;
private int num;
public Car(String color, int num) {
super();
this.color = color;
this.num = num;
}
@Override
public String toString() {
return "Car [name=" + name + ", color=" + color + ", num=" + num + "]";
}
}
package com.spring;
public class Person {
private String name;
private int age;
private Car car;
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 Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
}
}
测试类:
package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//1.创建spring IOC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = (Car) ctx.getBean("car");
//System.out.println(car.toString());
Person person = (Person) ctx.getBean("person");
System.out.println(person);
}
}
运行结果为:
Person [name=xiao, age=22, car=Car [name=null, color=green, num=22]]