對Spring IOC容器相關整理(二)

一、命名空間 :Beans 下的元素及屬性html

<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-3.0.xsd" >
    <description>rabbitmq 鏈接服務配置</description>
    <!--步驟一、配置連接工廠-->
    <bean id="connectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <property name="host" value="${mq.address}"/>
        <property name="port" value="${mq.port}"/>
        <property name="password" value="${mq.pwd}"/>
        <property name="username" value="${mq.user}"/>
        <property name="publisherConfirms" value="true"/>
        <property name="publisherReturns" value="true"/>
        <property name="virtualHost" value="${mq.vhost}"/>
        <property name="requestedHeartBeat" value="50"/>
    </bean>
 //.......
</beans>

對於配置XML文件 Spring 提供了不少的元素和屬性,用於對對象與其依賴關係進行描述。Spring的XML文件就像一張記錄詳細配料,火候等的菜譜。對於Spring XML文件,咱們通常經過以<beans>....</beans>包圍的元素開始配置。java

有關http://www.springframework.org/schema/beans 中對於beans 的定義可參見:標籤系列一:spring 中beans解釋以及beans標籤裏面的屬性spring

接下來我要整理一下關於beans 的相關的元素及屬性:網絡

beans命名空間下的元素編輯器

經過編輯器能夠輕易的找到在beans命名空間下,存在beans、bean、alias、description、import 五個元素存在。(也多是4個, 在http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 版中沒有beans元素,4.0版存在(默認最新版請把上文中的-3.0 去掉))ide

1.一、beans元素函數

beans元素是頂層(一般爲根)元素。容許定義全部嵌套bean定義的默認值。post

beans元素有本身的屬性:url

1.1.一、default-autowire 屬性:spa

default-autowire 有五個值 分別以下:

默認的值爲:no 即不啓用自動注入。

default:其實是會優先執行constructor而後是byType

byType:這個是會根據類型去注入,當找到了會直接注入,沒有找到不會報錯,可是找到多個會報No unique bean of type的錯誤

byName:這個會根據name注入

constructor:這個是經過構造注入

no:不啓用自動注入

1.1.二、default-autowire-candidates 屬性:

 default-autowire-candidates是候選者,自動裝配時即匹配則被包含。不匹配的排除在外。

default-autowire-candidates屬性的值容許使用模式字符串,例如咱們制定default-autowire-candidates=「*abc」,則全部以「abc」結尾的Bean都將被自動裝配。它還支持多個字符,能夠經過,空格 等分割。

1.1.三、default-init-method 和 default-destroy-method 屬性:

default-init-method="init" default-destroy-method="destroy"

 不少Bean都須要配置初始化方法和銷燬方法,那麼能夠在beans標籤中配置default-init-method和default-destroy-method來指定全部Bean的默認初始化方法和銷燬方法 (initdestroy 是bean中的方法)

 1.1.四、default-lazy-init 屬性:

spring配置默認default-lazy-init爲false,當屬性default-lazy-init設置成true時,sping不會再去加載整個對象實例圖,大大減小了初始化的時間,減小了spring的啓動時間。

1.1.五、default-merge 屬性:

 從Spring 2.0M2開始,beans支持default-merge= "true" 的定義,子類不須要從新定義父類的List型屬性中已定義過的內容 

1.1.6、profile 屬性:

將程序從一個環境遷移或切換到另外一個環境 定義環境名稱。

默認上下文中,添加spring.profiles.default的配置,以下:

<context-param>

    <param-name>spring.profiles.default</param-name>

    <param-value>development</param-value>

</context-param>

而對於spring.profiles.default,這裏須要說明下:在Spring的Profile中,Profile存在兩種狀態,一種爲默認加載的profile(spring.profiles.default),一種爲指定激活的profile(spring.profiles.active)。若是程序未指定active狀態的profile,那麼執行default狀態的profile,若是兩種狀態都指定,則優先執行或選擇active狀態的profile。


1.二、alias 元素(別名)

在對bean進行定義時,除了使用id屬性來指定名稱以外,爲了提供多個名稱,可使用alias標籤來指定。而全部的這些名稱都指向同一個bean,有時咱們指望能在當前位置爲那些在別處定義的bean引入別名。在XML配置文件中,可用單獨的<alias/>元素來完成bean別名的定義。如:

配置文件中定義了一個JavaBean

<bean id="resourceHolder" class="com.zk.demo1025.ResourceHolder"> </bean>

 

我要給這個JavaBean增長別名,以方便不一樣對象來調用。咱們就能夠這樣寫:

<alias name="resourceHolder" alias="resourceHolder1"/>

<alias name="resourceHolder" alias="resourceHolder2"/>

<alias name="resourceHolder" alias="resourceHolder3"/>


    <alias name="resourceHolder" alias="resourceHolder1,resourceHolder2,resourceHolder3"/>

或者是用name屬性來指定,如:

<bean id="resourceHolder" name="resourceHolder1,resourceHolder2,resourceHolder3 " class="com.zk.demo1025.ResourceHolder"> </bean>

1.三、description (描述)元素

description元素必須在beans 中的第一行,用於描述配置的信息。

1.4 import 元素

在Spring的配置文件,有時候爲了分模塊的更加清晰的進行相關實體類的配置。引入其餘模塊XML

當使用import元素時會提供一下選項:

其中,以 .xml 結尾的是項目中的配置文件。

1.默認狀況下,使用相對路徑來輔助查找配置文件

2.Spring提供了四種前綴標記來輔助查找配置文件:

  (1)[classpath:]:表示從classpath開始尋找後面的資源文件

  (2)[file:]:表示使用文件系統的方式尋找後面的文件(文件的完整路徑)

  (3)[classpath*:]:表示不只會在class路徑中去查找文件,還會在jar中去查找文件

  (4)[http:] :表示經過網絡地址查找文件


注:classpath:XXXXX:至關於/WIN-INF/classes/xxxxx

1.五、bean 元素

bean元素的屬性有不少:

經常使用屬性有:

  • id , id標籤是bean的惟一標識,IoC容器中bean的id標籤不能重複,不然報錯。
  • name ,name是bean的名稱標識,IoC容器中bean的name標籤不能重複同一個bean中能夠與id 重複(沒有發現不良反應)
  • class ,class屬性是bean經常使用屬性,爲bean的全限定類名,指向classpath下類定義所在位置
  • factory-method ,factory-method工廠方法屬性,經過該屬性,咱們能夠調用一個指定的靜態工廠方法,建立bean實例
  • factory-bean ,factory-bean就是生成bean的工廠對象,factory-bean屬性和factory-method屬性一塊兒使用
  • init-method ,init-method屬性是bean的初始方法,在建立好bean後調用該方法
  • destory-method ,destory-method屬性是bean的銷燬方法,在銷燬bean以前調用該方法,通常在該方法中釋放資源
  • scope,scope屬性表示bean的做用範圍(參見:對Spring IOC容器相關整理(一)
  • autowire ,autowire表示bean的自動裝配

 id標籤的值 在 同一個配置文件中是唯一的,在多個spring文件中存在相同的id 或 name後面引入的配置會覆蓋前面的bean

其他屬性有:

  • parent ,spring 中parent標籤是指:某個<bean>的父類。這個類能夠覆蓋parent的屬性
  • abstract ,使用abstract 屬性 定義公共的屬性。bean使用abstract=true時,能夠有class,也能夠沒有class,通常與parent 配合使用。
  • autowire -candidate,值有 true, false、default  。autowire-candidate="false" 表示該對象不參與自動注入
  • depends-on , depends-on適用於表面上看起來兩個bean之間沒有使用屬性之類的強鏈接的bean,可是兩個bean又確實存在先後依賴關係的狀況,被depends-on連接的bean 先建立,後銷燬,依賴他人的bean是先於被依賴bean銷燬的
  • lazy-init , 只有 true、false 用來指定bean是否在容器啓動時初始化,爲false時容器啓動時初始化  用途: 一般用於解決spring循環引用的問題:
  • primary ,primary的值有true和false兩個能夠選擇。默認爲false。當一個bean的primary設置爲true,而後容器中有多個與該bean相同類型的其餘bean,此時,當使用@Autowired想要注入一個這個類型的bean時,就不會由於容器中存在多個該類型的bean而出現異常。而是優先使用primary爲true的bean。不過,若是容器中不只有多個該類型的bean,並且這些bean中有多個的primary的值設置爲true,那麼使用byType注入仍是會出錯。

1.5.一、bean元素的子元素

 

由上圖能夠看到,bean元素中有7子元素

  • property:經過setter對應的方法注入 。spring配置中property做爲bean的屬性。也就是指一個類中的成員。同時這個成員必須有set方法。
  • description :描述,一個字符串,沒什麼好說的。
  • constructor-arg :經過構造函數注入
  • lookup-method :方法的覆蓋。注入bean的做用域小於當前bean時,但願每次能夠拿到最新的注入bean。
  • meta:一個額外的屬性,可使用  BeanDefinition的getAttribute(key);方法獲取,
  • qualifier:當bean的注入項有多個實現時,使用Qualifier指定要注入的bean的標識
  • replaced-method:方法的替換 ,要實現spring的MethodReplacer接口
  • 下面對每一個元素進行詳細介紹:

a、property 設值注入

property 元素屬性有 name、 ref 、value 三個。 其中 name 爲類中要注入依賴項的名字。須要有set方法。name值與setXXX 中XXX一致,與聲明的名字無關。

ref 爲引用項bean的id 或name 。value 值爲值類型

property 元素有如下子元素:

 ref: <property name="....." ref="......" />就是找當前配置文件裏的bean ,<ref bean ="....."/> 是尋找全局(能夠到其餘xml中)中的 bean;<ref>標籤裏 有3種屬性 <ref bean="尋找全局(能夠到其餘xml中)中的 bean"/>,<ref local="關聯當前xml的bean "/>,<ref parent="用於指定其依賴的父 JavaBean 定義"/>。4.0BeanXSD中 ref 元素上的local 屬性再也不受支持

bean: 內部 Bean:當 Spring IoC 容器中的 bean1 只會被 bean2 引用,而不會被容器中任何其餘 Bean 引用的時候,則能夠將這個 bean1 之內部 Bean 的方式注入到 bean2 中。

description: 描述,一個字符串

value: 爲屬性注入字面值

set: 當屬性爲 java.util.Set 的時候  能夠在集合上加 merge="true",容許與父類集合合併

<bean id="boss" class="***">
  <property name="favorites">
    <set>
      <value>唱歌</value>
      <value>運動</value>
      <value>讀書</value>
    </set>
  </property>
</bean>

 

array:當屬性爲 java.util.Array 的時候  能夠在集合上加 merge="true",容許與父類集合合併

        <property name="favs">
            <array>
                <value>足球</value>
                <value>籃球</value>
                <value>排球</value>
            </array>
        </property>

 

idref: idref元素只是一種防止錯誤的方法,能夠將容器中另外一個beanid(一個字符串值,而不是引用)傳遞給一個<constructor-arg/><property/>元素(在某種意義上等同於<value/>)

 

<bean id="theTargetBean" class="..."/>

<bean id="theClientBean" class="...">
<property name="targetName">
<idref bean="theTargetBean"/>
</property>
</bean>

 

 

 

list: 當屬性爲 java.util.List 的時候,能夠在集合上加 merge="true",容許與父類集合合併

<bean id="boss" class="***">
  <property name="favorites">
    <list>
      <value>唱歌</value>
      <value>運動</value>
      <value>讀書</value>
    </list>
  </property>
</bean>

 

map: 當屬性爲 java.util.Map 的時候 能夠在集合上加 merge="true",容許與父類集合合併

<bean id="boss" class="***">
  <property name="favorites">
    <map>
      <entry>
        <key><value>key01</value></key>
        <value>唱歌</value>
      </entry>
      <entry>
        <key><value>key02</value></key>
        <value>運動</value>
      </entry>
      <entry>
        <key><ref bean="keyBean" /></key>
        <ref bean="valueBean" />
      </entry>
    </map>
  </property>
</bean>

 

meta: 一個額外的屬性,可使用  BeanDefinition的getAttribute(key);方法獲取,

<meta key = "key" value = "values">

null: 須要爲某個 bean 的屬性注入一個 null 值,在這裏咱們須要使用專用的 <null/> 元素標籤,經過它能夠爲其餘對象的屬性注入 null 值。

props: 當屬性爲 java.util.Properties 的時候 能夠在集合上加 merge="true",容許與父類集合合併

<bean id="boss" class="***">
  <property name="favorites">
      <props>
        <prop key="p01">唱歌</prop>
        <prop key="p02">運動</prop>
        <prop key="p03">讀書</prop>
      </props>
    </properties>
  </property>
</bean>

 b、constructor-arg 構造注入

以下圖,constructor-arg 有以下屬性:

  • value :注入的字面值
  • ref:注入對其餘bean的引用
  • name:注入項的名稱
  • index:注入項在參數列表的序列號(從0開始)
  • type:注入項的類型

constructor-arg下的子元素以下:

與 property 屬性相同,不在贅述。

 c、lookup-method 方法注入

 能夠不是 抽象類型的方法

public abstract class FathorCarService {



    public void read(){
        CarService carService=look();
        System.out.println("睡覺,吃法,上班");
        carService.read();
    }

    protected abstract CarService look();

}


public class CarService {
    public void read(){
        System.out.println("讀書,看報,寫字");
    }


}


    public static void main(String[] args) {
        ClassPathXmlApplicationContext cx=new ClassPathXmlApplicationContext("classpath:spring/spring-config.xml");
        FathorCarService carService=(FathorCarService)cx.getBean("car2");
        carService.read();
    }



    <bean id="car" class="service.CarService" scope="prototype"/>
    <bean id="car2" class="service.FathorCarService">
        <lookup-method name="look" bean="car"/>
    </bean>

 如:

    protected  CarService look(){
        return null;
    }

一樣能夠進行方法注入。結果以下:

官方文檔中 注入方法簽名:

  1. public|protected要求方法必須是能夠被子類重寫和調用的;
  2. abstract可選,若是是抽象方法,CGLIB的動態代理類就會實現這個方法,若是不是抽象方法,就會覆蓋這個方法,因此沒什麼影響;
  3. return-type就是non-singleton-bean的類型咯,固然能夠是它的父類或者接口。
  4. no-arguments不容許有參數。

 d、replaced-method 方法替換

public  class FathorCarService {



    public void read(){
        CarService carService=look();
        System.out.println("睡覺,吃法,上班");
        carService.read();
    }

    protected  CarService look(){
        return null;
    }

}



public class CarService implements MethodReplacer {
    public void read(){
        System.out.println("讀書,看報,寫字");
    }


    @Override
    public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
        System.out.println("遛狗,跳繩,跑路");
        return null;
    }
}


    public static void main(String[] args) {
        ClassPathXmlApplicationContext cx=new ClassPathXmlApplicationContext("classpath:spring/spring-config.xml");
        FathorCarService carService=(FathorCarService)cx.getBean("car2");
        carService.read();
    }


    <bean id="car" class="service.CarService" scope="prototype"/>
    <bean id="car2" class="service.FathorCarService">
        <replaced-method name="read" replacer="car"/>
    </bean>

使用方法替換將本應該輸出

輸出爲:

 大概就這麼多了,若是有什麼疏漏的地方,望各位博友指出.....

相關文章
相關標籤/搜索