Spring筆記2——Spring中Bean的裝配

一、引言  

  Spring中,對象無需本身負責查找或建立與其關聯的其餘對象,而是由容器負責把須要相互協做的對象引用賦予各個對象。建立應用對象之間的協做關係的行爲一般稱爲 裝配(Wiring),這也是依賴注入的本質。

二、聲明Bean

  配置Bean的方式主要有兩種:基於XML文件的配置方式和基於Java註解的配置方式。傳統的基於XML文件的配置方式在聲明Bean時,Spring配置文件的根元素來源於Spring beans命名空間所定義的<beans>元素。除了beans命名空間外,Java自帶了多種XML命名空間,經過這些命名空間能夠配置Spring容器 。
  下圖爲一些常見的Spring命名空間:

 

簡單聲明Bean的實例:

     Bean類:
 package com.springinaction.springidol;
public class Juggler implements Performer {
     private int beanBags = 3;
 
     public Juggler(){
     }
 
     public Juggler( int beanBags){
            this. beanBags = beanBags;
     }
     
     public void perform() throws PerformanceException {
           System. out.println( "拋擲 "+ beanBags + "個豆袋子" );
     }
 }
     配置文件:
<?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.xsd" >
 
     <bean id ="duke" class= "com.springinaction.springidol.Juggler" >
            <constructor-arg value ="15" />
     </bean >         
</beans>

三、Spring的經常使用裝配Bean值的方法     java

<?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.xsd">
 
     <!--構造器注入值 -->
     <bean id ="duke" class= "com.springinaction.springidol.Juggler" >
            <constructor-arg value ="15" />
     </bean >
     <bean id ="sonnet29" class= "com.springinaction.springidol.Sonnet29" >
     </bean >
     <bean id ="poeticDuke" class= "com.springinaction.springidol.PoeticJuggler" >
            <constructor-arg  value ="15" />
            <!--構造器注入對象引用 -->
            <constructor-arg  ref ="sonnet29" />
     </bean >
     <!--經過工廠方法建立Bean,適合單例設計模式 -->
     <bean id ="theStage" class= "com.springinaction.springidol.Stage"
            factory-method= "getInstance">
     </bean >
 
     <!--初始化和銷燬Bean -->
     <bean id ="auditorium" class= "com.springinaction.springidol.Auditorium"
            init-method= "turnOnLights" destroy-method="turnOffLights" >
     </bean >
     <!--注入屬性值 -->
     <bean id ="kenny" class= "com.springinaction.springidol.Instrumentalist" >
            <!--注入簡單值 -->
            <property name ="song" value="Jingle Bells" />
            <!--注入引用 -->
            <property name ="instrument" ref="pinao" />
            <!-- 內部Bean(inner bean) -->
            <!-- <property name="instrument"> <bean class="com.springinaction.springidol.Saxophone"></bean>
                </property> -->
     </bean >
     <!--裝配集合 -->
     <bean id ="hank" class= "com.springinaction.springidol.OneManBand" >
            <property name ="instruments">
                 <list >
                      <ref bean ="pinao" />
                      <ref bean ="saxophon" />
                 </list >
            </property >
     </bean >
     <!--裝配Map集合 -->
     <bean id ="hank2" class= "com.springinaction.springidol.OneManBand2" >
            <property name ="instruments">
                 <map >
                      <entry key ="PINAO" value-ref="pinao" />
                      <entry key ="SAXOPHON" value-ref="saxophon" />
                 </map >
            </property >
     </bean >
     <!--裝配Properties集合 -->
     <bean id ="hank3" class= "com.springinaction.springidol.OneManBand3" >
            <property name ="instruments">
                 <props >
                      <prop key ="PINAO">TOOT TOOT TOOT</ prop>
                      <prop key ="SAXOPHON">PLINK PLINK PLINK</prop>
                 </props >
            </property >
     </bean >
     <!--裝配空值 -->
     <bean id="example" class="com.springinaction.springidol.OneManBand2">
           <property name="someNonNullProperty">
                <null />
           </property>
     </bean> 
     <bean id ="saxophon" class= "com.springinaction.springidol.Saxophone" ></bean >
     <bean id ="pinao" class= "com.springinaction.springidol.Pinao" ></bean >
</beans>

四、SPEL(Spring表達式語言)正則表達式

  Spring還可使用表達式進行裝配,Spring使用SPEL裝配的實例以下所示:     
<?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.xsd">
 
     <!-- 字面值 -->
     <bean id ="duke" class= "com.springinaction.springidol.Juggler" >
            <!-- 整形 -->
            <property name ="song" value="#{5}" />
            <!-- 混合表達 -->
            <property name ="song" value="The Value is #{5}" />
            <!--浮點數 -->
            <property name ="song" value="#{89.7}" />
            <!--科學計數法 -->
            <property name ="song" value="#{1e4}" />
            <!--單引號或雙引號爲字符串 -->
            <property name ="song" value="#{'string'}" />
            <property name ="song" value='#{"string"}' />
            <!--布爾值 -->
            <property name ="song" value="#{false}" />
     </bean >
 
     <!-- 引用Bean、Properties和方法 -->
     <bean id ="car1" class= "com.springinaction.springidol.Instrumentalist" >
            <!-- 使用SPEL表達式裝配Bean值 -->
            <property name ="instrument" value="#{saxophone}" />
            <!-- 使用SPEL表達式裝配屬性值 -->
            <property name ="song" value="#{kenny.song}" />
            <!-- 使用SPEL表達式調用其餘Bean的方法 -->
            <property name ="song" value= "#{songSelector.selectSong()?.toUpperCase()}" />
     </bean >
 
     <!-- 操做類,T()會調用類做用域的方法和常量 -->
     <bean id ="car1" class= "com.springinaction.springidol.Instrumentalist" >
            <!-- 使用SPEL表達式獲取PI值 -->
            <property name ="multiolier" value= "#{T(java.lang.Math).PI}" />
            <!-- 使用SPEL表達式獲取隨機數 -->
            <property name ="song" value= "#{T(java.lang.Math).random()}" />
     </bean >
 
     <!-- SPEL進行數值計算 -->
     <bean id ="car1" class= "com.springinaction.springidol.Instrumentalist" >
            <!-- 使用SPEL進行常規計算 -->
            <property name ="adjustedAmount" value= "#{counter.total+42}" />
            <!-- 使用SPEL進行乘法運算 -->
            <property name ="adjustedAmount" value="#{2 * T(java.lang.Math).PI * circle.radius}" />
            <!-- 使用SPEL進行除法運算 -->
            <property name ="adjustedAmount" value= "#{counter.total / counter.count}" />
            <!-- 使用SPEL進行求餘運算 -->
            <property name ="adjustedAmount" value= "#{counter.total % counter.count}}" />
            <!-- 不一樣於Java,SPEL還提供乘方運算 -->
            <property name ="adjustedAmount"
                 value= "#{2 * T(java.lang.Math).PI * circle.radius ^ 2}" />
            <!-- 使用SPEL還可使用+號進行字符串的鏈接 -->
            <property name ="adjustedAmount"
                 value= "#{performer.firstName + '' + performer.lastName}" />
     </bean >
 
     <!-- SPEL進行比較 -->
     <bean id ="car2" class= "com.springinaction.springidol.Instrumentalist" >
            <!-- 判斷條件是否成立,進行裝配布爾值屬性,而且Spring中使用le和ge替代<=和>=號 -->
            <property name ="equal" value="#{counter.total == 100}" />
     </bean >
 
     <!-- SPEL的邏輯表達式 and、or、not或! -->
     <bean id ="car1" class= "com.springinaction.springidol.Instrumentalist2" >
            <property name ="largeCircle"
                 value= "#{shape.kind == 'circle' and shape.perimeter gt 1000}" />
            <property name ="outOfStock" value= "#{!product.avaliable}" />
     </bean >
 
     <!-- SPEL的條件表達式 -->
     <bean id ="car1" class= "com.springinaction.springidol.Instrumentalist2" >
            <property name ="song"
                 value= "#{kenny.song != null ? kenny.song : 'Greensleeves'}" />
            <!-- 三元運算符的簡化形式 ,這被稱爲elvis運算符 -->
            <property name ="song" value="#{kenny.song ?: 'Greensleeves'}" />
     </bean >
 
     <!-- SPEL的正則表達式 -->
     <bean id ="car1" class= "com.springinaction.springidol.Instrumentalist2" >
            <property name ="validEmail"
                 value= "#{admin.email matches '[a-zA-Z0-9._%+-]+\\.com'}" />
     </bean >
</beans>

SPEL的重要功能,篩選集合實例:    

 <?xml version="1.0" encoding= "UTF-8"?>
<beans xmlns= "http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p"
     xmlns:util="http://www.springframework.org/schema/util"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
 
     <!-- 使用Spring設置列表 -->
     <util:list id ="cities">
            <bean class ="com.springinaction.springidol.spel.City" p:name= "Chicage1"
                 p:state= "1L" p:population ="111111111"></ bean>
            <bean class ="com.springinaction.springidol.spel.City" p:name= "Chicage2"
                 p:state= "2L" p:population ="211111111">
            </bean >
            <bean class ="com.springinaction.springidol.spel.City" p:name= "Chicage3"
                 p:state= "3L" p:population ="311111111">
            </bean >
            <bean class ="com.springinaction.springidol.spel.City" p:name= "Chicage4"
                 p:state= "4L" p:population ="411111111">
            </bean >
            <bean class ="com.springinaction.springidol.spel.City" p:name= "Chicage5"
                 p:state= "5L" p:population ="511111111">
            </bean >
            <bean class ="com.springinaction.springidol.spel.City" p:name= "Chicage6"
                 p:state= "6L" p:population ="611111111">
            </bean >
            <bean class ="com.springinaction.springidol.spel.City" p:name= "Chicage7"
                 p:state= "7L" p:population ="711111111">
            </bean >
            <bean class ="com.springinaction.springidol.spel.City" p:name= "Chicage8"
                 p:state= "8L" p:population ="811111111">
            </bean >
     </util:list >
 
     <!-- SPEL篩選集合 -->
     <bean id ="spelSelectSet" class= "com.springinaction.springidol.spel.ChooseCity" >
            <!-- 選擇第三個城市 -->
            <!-- <property name="chooseCitySet" value="#{cities[2]}"></property> -->
            <!-- 隨機選擇城市 -->
            <property name ="chooseCitySet"
                 value= "#{cities[T(java.lang.Math).random() * cities.size()]}"></property>
            <!-- 系統環境 -->
            <property name ="systemEnviorment" value= "#{systemEnvironment['JAVA_HOME']}" ></property >
            <!-- 系統配置信息 -->
            <property name ="systemProperties" value= "#{systemProperties['path']}"></property >
            <!-- 查詢集合成員.?[]運算符 -->
            <property name ="bigCities" value= "#{cities.?[population gt 400000000]}" ></property >
            <!-- 查詢第一個符合條件.^[]運算符 -->
            <property name ="firstBigCity" value= "#{cities.^[population gt 400000000]}" ></property >
            <!-- 查詢最後一個符合條件.$[]運算符 -->
            <property name ="lastBigCity" value= "#{cities.$[population gt 400000000]}" ></property >
            <!-- 集合投影,即將將每個成員中選取特有的屬性放入新集合中 ,運算符.![] -->
            <property name ="cityNames" value= "#{cities.?[population gt 400000000].![name + ',' +state]}"></ property>
     </bean >
</beans>
相關文章
相關標籤/搜索