spring可以把注入到IOC容器中的bean自动装配到指定的属性上。下面通过XML的方式进行自动装配需要的bean。
一、通过XML的方式进行自动装配
假设有两个类,Person和Car,现在需要把Car的bean装配到Person中的car属性上。在xml的配置中需要用到autowire属性。
类Car
package com.lzj.spring;
public class Car {
private String brand;
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
}
类Person
package com.lzj.spring;
public class Person {
private String name;
private Car car;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person [name=" + name + ", car=" + car + "]";
}
}
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="car" class="com.lzj.spring.Car">
<property name="brand" value="baoma"></property>
<property name="price" value="100000"></property>
</bean>
<!--用autowire属性指定通过name进行加载。person中有一个car的属性,由于person中设置了setCar方法,指定了utowire="byName"属性后,会把IOC中的id为car的bean注入到person中的car属性上-->
<bean id="person" class="com.lzj.spring.Person" autowire="byName">
<property name="name" value="lzj"></property>
</bean>
</beans>
另外:也可以指定autowire=”byType”,通过类型进行注入。由于prson中的car属性为Car类型的,spring 会在IOC中寻找是否有类型为Car的bean,如果找到了,注入到person中的car属性上。
未完。。。