Spring中的自动装配是怎么回事?

来源:互联网 发布:泗阳县12345网络问政 编辑:程序博客网 时间:2024/05/03 06:15

1:Car

package com.autowire;


public class Car {
private String brand;
 
  private int price;
 
public Car() {
super();

}

public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}


@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
  
}


 2:Address

package com.autowire;


public class Address {
private String city;
private String street;


public String getCity() {
return city;
}


public void setCity(String city) {
this.city = city;
}


public String getStreet() {
return street;
}


public void setStreet(String street) {
this.street = street;
}


@Override
public String toString() {
return "Address [city=" + city + ", street=" + street + "]";
}


}


  3:Person

package com.autowire;


public class Person {
 private String name;
 private Address address;
 private Car car;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person [name=" + name + ", address=" + address + ", car=" + car
+ "]";
}
 
}

4:beans-autowire.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"
xmlns:util="http://www.springframework.org/schema/util"
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.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
   <bean id="address" class="com.autowire.Address"
   p:city="beijing" p:street="故宫"></bean>
    <bean id="car" class="com.autowire.Car"
   p:brand="Audi" p:price="700000"></bean>
   <!-- 可以使用autowire属性自动装配的方式,byName根据bean的名字和当前setter风格的属性进行自动装配 -->
    <!-- byType如果有2个以上的bean是相同类,会报异常 -->
    <bean id="person" class="com.autowire.Person"
   p:name="Alice" autowire="byName"></bean>
</beans>

5:Main

package com.autowire;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Main {


public static void main(String[] args) {

ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-autowire.xml");
 //2:从IOC容器中获取Bean实例
Person person1=(Person)ctx.getBean("person");
System.out.println(person1);

}


}


0 0