一个bean注入另外一个bean
当Person类中有一个属性是Car,那么该如何配置呢
- Car类
package com.spring.ioc;
public class Car {
private String brand;
private double price;
public void setBrand(String brand) {
this.brand = brand;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
}
- Person类
package com.spring.ioc;
public class Person {
private String name;
private int age;
private Car car;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
}
}
- 配置文件
两种方式,一种是先创建一个全局的Car的bean,然后在Person bean中引入
第二种是在Person bean中直接引入一个内部Car bean。
<bean id="car" class="com.spring.ioc.Car">
<property name="brand" value="BMW"></property>
<property name="price" value="100"></property>
</bean>
<!-- 引入外面创建的bean -->
<bean id="person1" class="com.spring.ioc.Person">
<property name="name" value="小明"></property>
<property name="car" ref="car"></property>