property和constructor-arg設值注入
阿新 • • 發佈:2018-12-29
一、注入的方式
配置檔案的根元素是beans,每個元件使用bean元素來定義,如果使用設值注入,可以利用以下方式,來指定元件的屬性。
constructor-arg:通過建構函式注入。
property:通過setxx方法注入。
二、使用方法
(1)property的簡單使用
spring的xml配置檔案:
<bean id="baseInfo" class="com.learn.spring.baseInfo"> <property name="name" value="sky"/> <property name="age" value="24"/> </bean>
java檔案:
package com.learn.spring;
public class baseInfo {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
(2)constructor-arg的簡單使用spring的xml配置檔案:
<bean id="man" class="com.learn.spring.Man"> <!-- 當建構函式有多個引數時,可以使用index屬性,index屬性的值從0開始 --> <constructor-arg value="zzy" index="0"> </constructor-arg> <!-- 在使用構造子注入時,需要注意的問題是要避免構造子衝突的情況發生 如 man(String value) man(int value)建構函式衝突 使用type屬性制定引數型別,明確的告訴需要使用哪個建構函式 --> <constructor-arg value="10" type="int" index="1"> </constructor-arg> <constructor-arg> <list> <value>movie</value> <value>music</value> </list> </constructor-arg> <constructor-arg> <set> <value>Lady is GaGa</value> <value>GaGa is Lady</value> </set> </constructor-arg> <constructor-arg> <map> <entry key="zhangsan" value="male"></entry> <entry key="lisi" value="female"></entry> </map> </constructor-arg> <!-- 最後一個引數是boolean型別的引數,在配置的時候可以是true/false或者0/1 --> <constructor-arg index="5" value="0"> </constructor-arg> <constructor-arg> <props> <prop key="name">sky</prop> </props> </constructor-arg> </bean>
為了注入集合屬性,Spring提供了list,map,set和props標籤,分別對應List,Map,Set和Properties,我們甚至可以巢狀的使用它們(List of Maps of Sets of Lists)。
java檔案:
public class Man {
private String name;
private int age;
private List hobby;
private Map friends;
private Set set;
private boolean ifMarried;
private Properties properties;
public Man() {
}
public Man(String name, int age, List hobby, Map friends, Set set, boolean ifMarried, Properties properties) {
this.name = name;
this.age = age;
this.hobby = hobby;
this.friends = friends;
this.set = set;
this.ifMarried = ifMarried;
this.properties = properties;
}
}