property和constructor-arg的使用,constructor-arg

來源:互聯網
上載者:User

property和constructor-arg的使用,constructor-arg
(標註依稀)由於好久沒去看spring的東西,以前的知道差不多都忘記了,今天重新學習一下如何使用,以後在慢慢的一個一個知識點的深究。我發現學過的東西還是要記錄下來,否則以後又要重新找資料。純屬個人學習筆記。 

一:依賴注入的方式 

  constructor-arg:通過建構函式注入。 
  property:通過setxx方法注入。 

二:constructor-arg的簡單使用 

  java代碼 

    public class Man {private String name ;private int age;private List hobby;private Map  friends;private Set  set;private boolean ifMarried;public Man() {}    public Man(String name, int age,List hobby,Map friends,Set    set,boolean ifMarried){    this.name = name;    this.age = age;    this.hobby = hobby;    this.friends = friends;    this.set = set;    this.ifMarried = ifMarried;    }        public String getInfo(){        String info = "姓名:"+this.name+"\n年齡:"+this.age+"\n愛好:"+this.hobby+"\n朋友:"+this.friends+"\n婚否:"+this.ifMarried+"\n其他的:"+this.set;        return info;    }}   
  xml設定檔 

<bean id="man" class="com.spring.test.man.Man">   <constructor-arg value="zzy" index="0" >   </constructor-arg>      <constructor-arg value="10" 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="liuhua" value="man"></entry>          <entry key="xujinglei" value="female"></entry>       </map>   </constructor-arg>      <constructor-arg index="5" value="0">   </constructor-arg></bean>

最後一個參數ifMarried是一個boolean類型的參數,在配置的時候可以是true/false或者0/1; 

二:property的簡單使用 
  java代碼: 
public class Doctor {private String name;private String sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public void init(){System.out.println("88888888888");}public void init(String name,String sex){this.name = name;this.sex = sex;}}
xml設定檔: 

  <bean id="doctor" class="com.spring.test.man.Doctor" init-method="init">  <property name="name" value="doctor"></property>  <property name="sex" value="i don't know"></property></bean>

在這裡我配置了一個init-method="init"表示在容易執行個體化這個doctor的時候,調用一個Doctor類的init方法,本來還以為可以通過這個init方法來注入要注入的資訊,但是嘗試過後才知道這個init方法是不能帶參數的。 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.