03-spring学习-自动装配
自动装配
新建person类:
package com.spring.bean.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 + "]"; } }
新建Car类:
package com.spring.bean.autowire; 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 + "]"; } }
Address类:
package com.spring.bean.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 + "]"; } }
配置文件:
<bean id="address" class="com.spring.bean.autowire.Address" p:city="北京" p:street="芙蓉观"></bean> <bean id="car" class="com.spring.bean.autowire.Car" p:brand="奥迪" p:price="3000"></bean> <bean id="person" class="com.spring.bean.autowire.Person" p:name="汤姆" p:address-ref="address" p:car-ref="car"></bean>
使用:
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-autowire.xml"); Person person=(Person) ctx.getBean("person"); System.out.print(person);
运行:
改成自动装配:
byName:可以使用autowire属性自动装配的方式,byName根据bean的名字和当前bean的setter风格的属性名自动装配。
<bean id="address" class="com.spring.bean.autowire.Address" p:city="北京" p:street="芙蓉观"></bean> <bean id="car" class="com.spring.bean.autowire.Car" p:brand="奥迪" p:price="3000"></bean> <!-- 可以使用autowire属性自动装配的方式,byName根据bean的名字和当前bean的setter风格的属性名自动装配 , 若有匹配的,则进行自动装配,若没有匹配的不装配--> <bean id="person" class="com.spring.bean.autowire.Person" p:name="汤姆" autowire="byName"></bean>
byType:
可以使用autowire属性自动装配的方式,byName根据bean的类型和当前bean的setter风格的类型进行自动装配 ,
但是,如果IOC容器中有一个以上的类型匹配的bean,则抛异常。
<!-- 可以使用autowire属性自动装配的方式,byName根据bean的类型和当前bean的setter风格的类型进行自动装配 , 但是,如果IOC容器中有一个以上的类型匹配的bean,则抛异常--> <bean id="person" class="com.spring.bean.autowire.Person" p:name="汤姆" autowire="byType"></bean>