AutoWire 有 ByType ,ByName两种主要使用方式
public class Boss { @Autowired private Car car; public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public Office getOffice() { return office; } public void setOffice(Office office) { this.office = office; } @Autowired private Office office; //省略 get/setter @Override public String toString() { return "Boss [car=" + car + ", office=" + office + "]"; } } public class Car { String brand; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } String price; } import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); Boss boss = (Boss) ctx.getBean("boss"); System.out.println(boss); } } public class Office { private String officeNo; public String getOfficeNo() { return officeNo; } public void setOfficeNo(String officeNo) { this.officeNo = officeNo; } }
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="boss" class="Boss"> </bean> <bean id="office1" class="Office"> <property name="officeNo" value="002"/> </bean> <bean id="office2" class="Office"> <property name="officeNo" value="003"/> </bean> <bean id="car" class="Car" scope="singleton"> <property name="brand" value="hongqi"/> <property name="price" value="200000"/> </bean> </beans>
上面这种写法会报异常,因为有多个Office类型,又没有同名id.
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="boss" class="Boss"> </bean> <bean id="office" class="Office"> <property name="officeNo" value="002"/> </bean> <bean id="office2" class="Office"> <property name="officeNo" value="003"/> </bean> <bean id="car" class="Car" scope="singleton"> <property name="brand" value="红旗CA72"/> <property name="price" value="2000"/> </bean> </beans>
这种写法会选择id="office".