例如我们现在有一个Computer类:
public class Computer { private String cpu; private String hdd;//硬盘 private String mainboard;//主板 private int type;//版本号 //显示配置信息 public void show() { System.out.println("cpu:"+cpu+" hdd:"+hdd+"mainboard: " +mainboard); System.out.println("type: "+type); } public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } public String getHdd() { return hdd; } public void setHdd(String hdd) { this.hdd = hdd; } public String getMainboard() { return mainboard; } public void setMainboard(String mainboard) { this.mainboard = mainboard; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
1、基本类型值或者String类型的值的注入,property中name与类中定义的属性名一致,值由value指定,int类型的值也可以直接指定value="5"
(1)设值注入
原理:创建对象后,利用反射调用对象的setter方法,为相关的属性注入值
<bean id = "computer" class="com.zlc.test.Computer"> <property name="cpu" value="i7"></property> <property name="hdd" value="4G"></property> <property name="mainboard" value="bestone"></property> <property name="type" value="5"></property> </bean>
(2)构造注入
原理:在创建对象时,利用反射调用该带参的构造函数创建对象实例
原Computer改为这样:
public class Computer { private String cpu; private String hdd;//硬盘 private String mainboard;//主板 private int type;//版本号 //显示配置信息 public void show() { System.out.println("cpu:"+cpu+" hdd:"+hdd+"mainboard: " +mainboard); System.out.println("type: "+type); } public Computer(String cpu,String hdd,String mainboard,int type) { this.cpu = cpu; this.hdd = hdd; this.mainboard = mainboard; this.type = type; } }
<bean id = "computer" class="com.zlc.test.Computer"> <constructor-arg index="0" value="i7"></constructor-arg> <constructor-arg index="1" value="4G"></constructor-arg> <constructor-arg index="2" value="good"></constructor-arg> <constructor-arg index="3" value="5"></constructor-arg> </bean>
以上的index用来标识参数在构造器中的顺序,从0开始计数
2、引用类型值的注入
(1)设值注入:
原Computer改为这样:
public class Computer { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
在applicationContext.xml配置为:
<bean id = "computer" class="com.zlc.test.Computer"> <property name="date" ref="date"></property> </bean> <bean id="date" class="java.util.Date"> </bean>
(2)构造注入
原Computer改为这样:
public class Computer { private Date date; public Computer(Date date) { this.date = date; } }
在applicationContext.xml配置为:
<bean id = "computer" class="com.zlc.test.Computer"> <constructor-arg index="0" ref="date"></constructor-arg> </bean> <bean id="date" class="java.util.Date"> </bean>
原文:https://www.cnblogs.com/zlingchao/p/9404399.html