spring中建構函式注入,spring建構函式注入

來源:互聯網
上載者:User

spring中建構函式注入,spring建構函式注入

spring中建構函式注入,簡單來說,就是通過beans.xml中,設定相應的值,並且通過bean類中的建構函式進行注入這些值。

檔案結構


Goods類

package com.test.innerbean;public class Goods {private String goodsName;private int price;public Goods(String name,int price){goodsName=name;this.price=price;}public void say(){System.out.println("goodsname:"+goodsName+" price:"+price);}}

beans.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://www.springframework.org/schema/beans              http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">    <bean id="goods" class="com.test.innerbean.Goods">   <constructor-arg  value="茶杯"></constructor-arg>   <constructor-arg value="12"></constructor-arg>    </bean>      </beans>


測試類別

package com.test.innerbean;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;public class Test {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubBeanFactory factory=new XmlBeanFactory(new ClassPathResource("com/test/innerbean/beans.xml"));Goods goods=(Goods)factory.getBean("goods");goods.say();}}

輸出結果



我們可以看到,能夠產生Goods類的一個執行個體,並且對這個執行個體進行輸出測試,發現也的確獲得了相應的值。


為何使用set注入,一定要給類提供一個無參的建構函式,否則Spring不可以執行個體化類的

一個類中無建構函式的話,系統會自動添加一個預設無參建構函式,
而如果寫過建構函式, 系統將不會再次添加,
一般寫代碼的時候, 最好把無參建構函式顯示的寫出來。
 
Spring的構造方法注入

分別給構造方法的參數賦值,例如建構函式有三個參數:



 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.