spring容器的註入方式總結
阿新 • • 發佈:2018-08-02
return ret code spring ons 一個 ont .com print
例如我們現在有一個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>
spring容器的註入方式總結