Spring Bean注入的幾種方式(轉)

一.從XML文件中獲取Bean的方法

1.採用BeanFactory方式


        Resource rs = new FileSystemResource("beans-config.xml");
        BeanFactory factory = new XmlBeanFactory(rs);
        HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
採用BeanFactory方式,能夠利用XmlBeanFactory從xml配置文件中得到bean,也可使用其它方式,好比利用PropertiesFactoryBean從.property文件中得到。

2.採用ApplicationContext方式
採用BeanFactory對簡單的應用程序來講就夠了,能夠得到對象管理上的便利性。
可是要獲取一些特點和高級的容器功能,能夠採用ApplicationContext。
ApplicationContext提供了一些高級的功能,好比:
1.提供取得資源文件更方便的方法
2.提供文字消息解析的方法
3.支持國際化(i18n)消息
4.能夠發佈事件,對事件感興趣的Bean能夠接收這些事件

Spring創始者建議採用ApplicationContext取代BeanFactory。
在實現ApplicationContext藉口的類中,經常使用的幾個:
FileSystemXmlApplicationContext:
能夠指定XML定義文件的相對路徑或
者絕對路徑來讀取定義文件。

ClassPathXmlApplicationCOntext:
能夠從classpath中讀取XML文件


XmlWebApplicationCOntext:
從Web應用程序的文件架構中,指定相對位置來讀取定義文件。
一個簡單的例子:

package cn.blogjava.hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringDemo {
    public static void main(String[] args) {
        ApplicationContext context =
            new FileSystemXmlApplicationContext("beans-config.xml");       
        HelloBean helloBean = (HelloBean)context.getBean("helloBean");
        System.out.print("Name: ");
        System.out.println(helloBean.getName());
        System.out.print("Word: ");
        System.out.println(helloBean.getHelloWord());
    }
}

二.Type 2 IoC, Type 3 IoC
Type2是 利用setter方法完成依賴注入,這是Spring鼓勵的。但也容許使用Type 3注入, 也就是利用構造函數完成注入。
例如:

package cn.blogjava.hello;

public class HelloBean {
   
    private String helloWord;
    private String name;
   
    public HelloBean() {
       
    }

    public HelloBean(String helloWord, String name) {
        this.helloWord = helloWord;
        this.name = name;
    }   
   
    public String getHelloWord() {
        return helloWord;
    }

    public void setHelloWord(String helloword) {
        this.helloWord = helloword;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
   
}

配置文件:
beans-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="helloBean" class="cn.blogjava.hello.HelloBean" >
        <constructor-arg index="0">
            <value>YYY!</value>
        </constructor-arg>
        <constructor-arg index="1">
            <value>Hello!</value>
        </constructor-arg>
    </bean>
</beans>
三.屬性參考
若是在Bean文件中已經有一個定義的Bean實例,可讓某個屬性直接參考這個實例。

package cn.blogjava.hello;

import java.util.Date;

public class HelloBean {
   
    private String helloWord;
    private Date date;
   
    public HelloBean() {
       
    }

   
    public String getHelloWord() {
        return helloWord;
    }

    public void setHelloWord(String helloword) {
        this.helloWord = helloword;
    }
   
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

配置文件
beans-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="dateBean" class="java.util.Date"/>
    <bean id="helloBean" class="cn.blogjava.hello.HelloBean" >
        <property name="helloWord">
            <value>Hello!</value>
        </property>

        <property name="date">
            <ref bean="dateBean" />
        </property>               
    </bean>
</beans>
若是某個Bean的實例只被參考一次,能夠直接在屬性定義時使用<bean>標籤,並僅須要指定其"class"屬性便可。


        <property name="date">
            <bean class="java.util.Date" />
        </property>             

四.自動綁定
byType

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="dateBean" class="java.util.Date"/>
    <bean id="helloBean" class="cn.blogjava.hello.HelloBean"  autowire="byType">
        <property name="helloWord">
            <value>Hello!</value>
        </property>
        <property name="name">
            <value>YYY!</value>
        </property>            
    </bean>
</beans>這裏並無指定helloBean的data屬性,而是經過自動綁定,指定了"byType",因此會根據helloBean的setDate()方法所接受的類型,來判判定義文件中是否有相似的對象,並將之設定給helloBean的setDate(),若是沒法完成綁定,會拋異常。

byName
根據id屬性上指定的別名是否與setter名稱一致來綁定。沒法綁定,僅維持未綁定狀態,不拋異常。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="date" class="java.util.Date"/>
    <bean id="helloBean" class="cn.blogjava.hello.HelloBean"  autowire="byName">
        <property name="helloWord">
            <value>Hello!</value>
        </property>
        <property name="name">
            <value>YYY!</value>
        </property>            
    </bean>
</beans> autowire="constructor"
根據構造方法上的參數類型,來匹配。沒法綁定拋異常。
autowire="autodetect"
會試着用constructor,byType等方式來創建依賴關係。

加入依賴檢查
依賴檢查有4種方式:
simple只檢查簡單的屬性,例如int或者String類型對象是否完成依賴。
objects檢查對象類型的屬性是否完成依賴。
all檢查全部的屬性,none是默認值,不檢查依賴性。


    <bean id="helloBean" class="cn.blogjava.hello.HelloBean"  autowire="autodetect" dependency-check="all">
        <property name="helloWord">
            <value>Hello!</value>
        </property>
        <property name="name">
            <value>YYY!</value>
        </property>            
    </bean>
五.集合對象的注入
對於像數組、List、Set、Map等集合對象, 在注入前若必須填充一些對象到集合中,而後再將集合對象注入到Bean中時,能夠交給Spring的IoC容器自動維護或者生成集合對象,並完成依賴注入。

SomeBean.java

package cn.blogjava.hello;

import java.util.List;
import java.util.Map;

public class SomeBean {
   
    private String[] someStrArray;
    private Some[] someObjectArray;
    private List someList;
    private Map someMap;
    public List getSomeList() {
        return someList;
    }
    public void setSomeList(List someList) {
        this.someList = someList;
    }
    public Map getSomeMap() {
        return someMap;
    }
    public void setSomeMap(Map someMap) {
        this.someMap = someMap;
    }
    public Some[] getSomeObjectArray() {
        return someObjectArray;
    }
    public void setSomeObjectArray(Some[] someObjectArray) {
        this.someObjectArray = someObjectArray;
    }
    public String[] getSomeStrArray() {
        return someStrArray;
    }
    public void setSomeStrArray(String[] someStrArray) {
        this.someStrArray = someStrArray;
    }
   
   
}

Some.java

package cn.blogjava.hello;

public class Some {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }   
   
    public String toString(){
        return name;
    }
}

beans-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="some1" class="cn.blogjava.hello.Some">
        <property name="name">
            <value>YYY</value>
        </property>
    </bean>
   
    <bean id="some2" class="cn.blogjava.hello.Some">
        <property name="name">
            <value>BYF</value>
        </property>
    </bean>
   
    <bean id="someBean" class="cn.blogjava.hello.SomeBean">
        <property name="someStrArray">
            <list>
                <value>Hello!</value>
                <value>Welcome!</value>
            </list>
        </property>
       
        <property name="someObjectArray">
            <list>
                <ref bean="some1"/>
                <ref bean="some2"/>
            </list>
        </property>
       
        <property name="someList">
            <list>
                <ref bean="some1"/>
                <ref bean="some2"/>           
            </list>
        </property>
       
        <property name="someMap">
            <map>
                <entry key="MapTest">
                    <value>Hello YYY!</value>
                </entry>
                <entry key="someKey1">
                    <ref bean="some1" />
                </entry>
            </map>
        </property>
    </bean>
       
    <bean id="helloBean" class="cn.blogjava.hello.HelloBean" >
    </bean>
</beans>
測試類:SpringDemo.java
package cn.blogjava.hello;

import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringDemo {
    public static void main(String[] args) {
        ApplicationContext context =
            new FileSystemXmlApplicationContext("beans-config.xml");       
        SomeBean someBean = (SomeBean)context.getBean("someBean");

        //取得數組類型依賴注入對象
        String[] strs = (String[])someBean.getSomeStrArray();
        Some[] somes = (Some[])someBean.getSomeObjectArray();
        for(int i=0; i < strs.length; i++){
            System.out.println(strs[i] + "," + somes[i].getName());
        }
       
        System.out.println();
        //取得List類型依賴注入對象
        List someList = someBean.getSomeList();
        for(int i=0; i < someList.size(); i++) {
            System.out.println(someList.get(i));
        }
       
        System.out.println();
        //取得Map類型依賴注入對象
        Map someMap = someBean.getSomeMap();
        System.out.println(someMap.get("MapTest"));
        System.out.println(someMap.get("someKey1"));
    }
}



  list, set, map和props元素分別用來設置類型爲List,Set,Map和Propertis的屬性值。分別用來爲bean傳入集合值。
對應的spring的配置文件舉例以下:

1.<? xml version="1.0" encoding="gb2312" ?>   
2. <! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"  
3. "http://www.springframework.org/dtd/spring-beans.dtd" >   
4.   
5. < beans >   
6.   
7.  < bean  id ="chinese"  class ="Chinese" >   
8.  < property  name ="friends" >   
9.             < list >   
10.                 < value > 張三 </ value >   
11.                 < value > 李四 </ value >   
12.                 < value > 王五 </ value >   
13.             </ list >   
14.   </ property >   
15.   < property  name ="score" >   
16.             < map >   
17.                 < entry  key ="數學" >   
18.                     < value > 60 </ value >   
19.                 </ entry >   
20.                 < entry  key ="英語" >   
21.                     < value > 70 </ value >   
22.                 </ entry >   
23.                 < entry  key ="語文" >   
24.                     < value > 80 </ value >   
25.                 </ entry >   
26.                 < entry  key ="物理" >   
27.                     < value > 90 </ value >   
28.                 </ entry >   
29.                 < entry  key ="化學" >   
30.                     < value > 95 </ value >   
31.                 </ entry >   
32.             </ map >   
33.   </ property >   
34.   < property  name ="basicInfo" >   
35.             < props >   
36.                 < prop  key ="身高" > 165 </ prop >   
37.                 < prop  key ="體重" > 45kg </ prop >   
38.                 < prop  key ="學歷" > 大學本科 </ prop >   
39.             </ props >   
40.    </ property >   
41.    < property  name ="interest" >   
42.             < set >   
43.                 < value > 唱歌 </ value >   
44.                 < value > 跳舞 </ value >   
45.                 < value > 書法 </ value >   
46.             </ set >   
47.    </ property >   
48.   
49. </ bean >   
50.   
51. </ beans >   




1.public   class  Chinese  implements  People   ...{  
2.     private  List friends  =   new  ArrayList();  
3.     private  Map score  =   new  HashMap();  
4.     private  Properties basicInfo  =   new  Properties();  
5.     private  Set interest  =   new  HashSet();  
6.     // 省略對應set方法   
7.     .  
8.} 
 
 
問:爲何數組啊 屬性變量都要在bean裏面設定呢?
答:維護方便。維護數據時,只須要改配置文件。
相關文章
相關標籤/搜索