标签:
bean的配置除了有手动配置,还有自动装配这一说法,具体怎么操作,如下代码事例。
自动装配可根据bean的名称与配置bean属性名称的对应进行配置,也可根据bean的类型与配置bean属性的类型进行配置。
1.自动配置 byName
person类
1 package com.org.spring.beans; 2 3 public class Person { 4 private String name; 5 private int age; 6 private Car car; 7 8 @Override 9 public String toString() { 10 return "Person [name=" + name + ", age=" + age + ", car=" + car + "]"; 11 } 12 13 public Person(){ 14 15 } 16 public Person(String name, int age, Car car) { 17 super(); 18 this.name = name; 19 this.age = age; 20 this.car = car; 21 } 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 public void setAge(int age) { 28 this.age = age; 29 } 30 31 public void setCar(Car car) { 32 this.car = car; 33 } 34 35 36 }
xml配置信息
1 <bean id="car" class="com.org.spring.beans.Car"> 2 <constructor-arg value="audi"></constructor-arg> 3 <constructor-arg value="shanghai"></constructor-arg> 4 <constructor-arg value="300000"></constructor-arg> 5 </bean> 6 <bean id="person2" class="com.org.spring.beans.Person" p:name="tom" p:age="20" autowire="byName"></bean>
运行结果
Person [name=tom, age=20, car=Car [brand=audi, crop=shanghai, price=300000.0, maxSpeed=0]]
2.自动配置 byType
xml配置信息
1 <bean id="car2" class="com.org.spring.beans.Car"> 2 <constructor-arg value="audi"></constructor-arg> 3 <constructor-arg > 4 <value><![CDATA[<shanghai>]]></value> 5 </constructor-arg> 6 <constructor-arg value="300000" type="int"> 7 8 </constructor-arg> 9 </bean> 10 <bean id="person3" class="com.org.spring.beans.Person" p:name="tom" p:age="20" autowire="byType"></bean>
结果显示
Person [name=tom, age=20, car=Car [brand=audi, crop=<shanghai>, price=0.0, maxSpeed=300000]]
使用该方式自动装配需要注意的是,当xml中存在多个类型一样的bean时,就会出现问题报错。
标签:
原文地址:http://www.cnblogs.com/bojuetech/p/4903953.html