Address類 public class Address { private String city; private String street; set和get方法... @Override public String toString() { return "Address [city=" + city + ", street=" + street + "]"; } } Car類 public class Car { private String brand; private double price; set和get方法... @Override public String toString() { return "Car [brand=" + brand + ", price=" + price + "]"; } } Person類 public class Person { private String name; private Address address; private Car car; set和get方法... @Override public String toString() { return "Person [name=" + name + ", address=" + address + ", car=" + car + "]"; } } XMl配置 <bean id="address" class="com.wzq.spring.bears.autowire.Address" p:city="Chongqing" p:street="Liangping"></bean> <bean id="car" class="com.wzq.spring.bears.autowire.Car" p:brand="Audi" p:price="300000"></bean> <!-- autowire="byName"根據(jù)名字指定自動裝配的方式.根據(jù)bean風格的屬性名進行自動裝配,若沒有匹配的不裝配 autowire="byTypr"根據(jù)類型自動裝配,若IOC容器中有一個以上的類型匹配,則拋出異常 --> <bean id="perosn" class="com.wzq.spring.bears.autowire.Person" p:name="WEIZUQING" autowire="byName"></bean> main方法 public class Mian { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); Person car = (Person) ctx.getBean("perosn"); System.out.println(perosn); } } |
|