程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Spring學習筆記之 Spring IOC容器(二),學習筆記ioc

Spring學習筆記之 Spring IOC容器(二),學習筆記ioc

編輯:JAVA綜合教程

Spring學習筆記之 Spring IOC容器(二),學習筆記ioc


 

 本節主要內容:
    1. 給MessageBean注入參數值
    2. 測試Spring自動組件掃描方式
    3. 如何控制ExampleBean實例化方式
    4. 使用注解方式重構JdbcDataSource, UserDAO, UserService

 

1 給MessageBean注入參數值

1.1 問題

Spring可以通過配置文件為bean注入多種類型的屬性, MessageBean類用於演示Spring的多種類型數據的注入方式, 這些類型數據和注入方式包括:

1. 注入基本值。

2. 注入Bean對象(請參考Unit 1案例)。

3. 直接集合注入。

4. 引用方式集合注入

5. 注入Spring表達式值。

6. 注入null或空字符串。

1.2 步驟

步驟一:新建工程,導入Spring API jar包

新建名為SouvcSpringIoC_02的web工程,在該工程導入5個jar包。

  commons-logging.jar spring-core.jar spring-context.jar spring-beans.jar spring-expression.jar   網盤下載jar包 :http://yunpan.cn/cQJhPMPRZeLH7  訪問密碼 2bf8

 

步驟二:新建Spring配置文件

在src目錄下,新建Spring配置文件applicationContext.xml。該文件名為Spring默認的配置文件名,也可以自由定義名稱。

applicationContext.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd">






</beans>
復制代碼

 

 

步驟三:新建類MessageBean 添加基本值屬性

新建類MessageBean,在該類中添加如下代碼中的四個屬性,並生成這幾個屬性對應的getter和setter方法;最後在execute方法獲取這幾個屬性的信息,代碼如下所示:

復制代碼
package com.souvc.bean;

public class MessageBean {
    private String moduleName;
    private int pageSize;
    private String username;
    private String password = "";

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getModuleName() {
        return moduleName;
    }

    public void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public String execute() {
        System.out.println("moduleName=" + moduleName);
        System.out.println("pageSize=" + pageSize);
        System.out.println("username=" + username);
        System.out.println("password=" + password);
        System.out.println("---List信息如下---");
        return "success";
    }

}
復制代碼

 

步驟四:修改applicationContext.xml文件, 增加屬性基本值注入

修改applicationContext.xml文件,為MessageBean的四個屬性注入基本參數值,代碼如圖-3所示:

    <bean id="messagebean" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="測試基本屬性"></property>
        <property name="pageSize" value="5"></property>
        <property name="username" value="daliu_it"></property>
        <property name="password" value="123456"></property>
    </bean>

 

步驟五:新建類Test1, 添加測試方法獲取MessageBean對象測試注入結果

新建類Test1,在類中使用ApplicationContext的方式實例化Spring容器,獲取MessageBean對象,並調用execute方法。

復制代碼
@Test
    public void test1() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        System.out.println(ac);

        MessageBean messagebean = ac.getBean("messagebean", MessageBean.class);
        System.out.println(messagebean.toString());
        messagebean.execute();
    }
復制代碼

 

步驟六:運行Test1類, 測試注入結果

運行Test1類,控制台輸入結果

復制代碼
org.springframework.context.support.ClassPathXmlApplicationContext@65b4fad5: startup date [Wed Jun 17 11:16:13 CST 2015]; root of context hierarchy
com.souvc.bean.MessageBean@5d3e754f
moduleName=測試基本屬性
pageSize=5
username=daliu_it
password=123456
---List信息如下---
復制代碼

 

控制台輸出所示的信息,說明獲取到了注入的基本屬性值。

 

步驟七:為MessageBean添加集合屬性,用於注入集合測試

1. 修改類MessageBean,在該類中添加如下加粗代碼中的四個屬性,並生成這幾個屬性對應的getter和setter方法;最後在execute方法獲取這幾個屬性的信息,代碼如下所示:

 
  •     private List<String> someList;
  •     private Set<String> someSet;
  •     private Map<String,Object> someMap;
  •     private Properties someProps;


 


復制代碼
package com.souvc.bean;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MessageBean {
    private String moduleName;
    private int pageSize;
    private String username;
    private String password = "";

    
     private List<String> someList;
     private Set<String> someSet;
     private Map<String,Object> someMap;
     private Properties someProps;
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getModuleName() {
        return moduleName;
    }

    public void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    
    
    public List<String> getSomeList() {
        return someList;
    }

    public void setSomeList(List<String> someList) {
        this.someList = someList;
    }

    public Set<String> getSomeSet() {
        return someSet;
    }

    public void setSomeSet(Set<String> someSet) {
        this.someSet = someSet;
    }

    public Map<String, Object> getSomeMap() {
        return someMap;
    }

    public void setSomeMap(Map<String, Object> someMap) {
        this.someMap = someMap;
    }

    public Properties getSomeProps() {
        return someProps;
    }

    public void setSomeProps(Properties someProps) {
        this.someProps = someProps;
    }

    
    
    public String execute() {
        System.out.println("moduleName=" + moduleName);
        System.out.println("pageSize=" + pageSize);
        System.out.println("username=" + username);
        System.out.println("password=" + password);
        System.out.println("---List信息如下---");
    
        for(String s : someList){
            System.out.println(s);
        }
        System.out.println("---Set信息如下---");
        for(String s : someSet){
            System.out.println(s);
        }
        System.out.println("---Map信息如下---");
        Set<String> keys = someMap.keySet();
        for(String key : keys){
            System.out.println(key+"="
                    +someMap.get(key));
        }
        System.out.println("---Properties信息如下---");
        Set<Object> keys1 = someProps.keySet();
        for(Object key : keys1){
            System.out.println(key+"="
                    +someProps.getProperty(key.toString()));
        }
        
        
        return "success";
    }

}
復制代碼

 

2. 修改applicationContext.xml文件,為MessageBean的四個屬性注入集合參數值:

復制代碼
<?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:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">



    <!-- 加載properties文件為bean
        <util:properties id="jdbcProperties"
        location="classpath:db.properties" /> -->


    <bean id="messagebean" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="測試基本屬性的注入"></property>
        <property name="pageSize" value="5"></property>
        <!-- 表達式注入 -->
        <property name="username" value="daliu_it"></property>
        <property name="password" value="123456"></property>
        <property name="someList">
            <list>
                <value>北京</value>
                <value>上海</value>
                <value>廣州</value>
            </list>
        </property>
        <property name="someSet">
            <set>
                <value>James Gosling</value>
                <value>Martin fowler</value>
                <value>Larry Ellision</value>
            </set>
        </property>
        <property name="someMap">
            <map>
                <entry key="1001" value="Java語言基礎"></entry>
                <entry key="1002" value="Java Web基礎"></entry>
                <entry key="1003" value="Spring使用基礎"></entry>
            </map>
        </property>
        <property name="someProps">
            <props>
                <prop key="username">root</prop>
                <prop key="password">1234</prop>
            </props>
        </property>
    </bean>


    <!-- 定義集合Bean 
        <util:list id="oneList">
        <value>Tom</value>
        <value>Andy</value>
        </util:list>
        <util:set id="oneSet">
        <value>James Gosling</value>
        <value>Martin fowler</value>
        </util:set>
        <util:map id="oneMap">
        <entry key="1001" value="Java語言基礎"></entry>
        <entry key="1002" value="Java Web基礎"></entry>
        </util:map>
        <util:properties id="oneProps">
        <prop key="username">root</prop>
        <prop key="password">1234</prop>
        </util:properties>
        
    -->

    <!-- 引用方式注入集合屬性 
        <bean id="messagebean2" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="資費管理"></property>
        <property name="pageSize" value="5"></property>
        <property name="username" value="andy"></property>
        <property name="password" value="123"></property>-->

    <!-- 引用方式注入集合屬性 
        <property name="someList" ref="oneList" />
        <property name="someSet" ref="oneSet" />
        <property name="someMap" ref="oneMap" />
        <property name="someProps" ref="oneProps" />
        </bean>-->
</beans>
復制代碼

 



3. 運行Test1類,控制台輸出結果所示:

  復制代碼
org.springframework.context.support.ClassPathXmlApplicationContext@42704baa: startup date [Wed Jun 17 11:30:43 CST 2015]; root of context hierarchy
com.souvc.bean.MessageBean@25961581
moduleName=測試基本屬性的注入
pageSize=5
username=daliu_it
password=123456
---List信息如下---
北京
上海
廣州
---Set信息如下---
James Gosling
Martin fowler
Larry Ellision
---Map信息如下---
1001=Java語言基礎
1002=Java Web基礎
1003=Spring使用基礎
---Properties信息如下---
password=1234
username=root
復制代碼

 

控制台輸出的信息,說明只需要通過配置Spring就可以為Bean注入集合參數值。

 

步驟八:測試引用方式集合注入

1.為Spring配置文件applicationContext.xml增加如下配置, 采用引用方式注入集合對象, 代碼參考如下:

復制代碼
<!-- 定義集合Bean -->
    <util:list id="oneList">
        <value>Tom</value>
        <value>Andy</value>
    </util:list>
    <util:set id="oneSet">
        <value>James Gosling</value>
        <value>Martin fowler</value>
    </util:set>
    <util:map id="oneMap">
        <entry key="1001" value="Java語言基礎"></entry>
        <entry key="1002" value="Java Web基礎"></entry>
    </util:map>
    <util:properties id="oneProps">
        <prop key="username">root</prop>
        <prop key="password">1234</prop>
    </util:properties>



    <!-- 引用方式注入集合屬性 -->
    <bean id="messagebean2" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="資費管理"></property>
        <property name="pageSize" value="5"></property>
        <property name="username" value="andy"></property>
        <property name="password" value="123"></property>

        <!-- 引用方式注入集合屬性 -->
        <property name="someList" ref="oneList" />
        <property name="someSet" ref="oneSet" />
        <property name="someMap" ref="oneMap" />
        <property name="someProps" ref="oneProps" />
    </bean>
復制代碼

 

 

2. 增加Test2類測試如上配置, Test2代碼如下:

復制代碼
package com.souvc.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.souvc.bean.MessageBean;

public class TestCase {

    @Test
    public void test1() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        System.out.println(ac);

        MessageBean messagebean = ac.getBean("messagebean", MessageBean.class);
        System.out.println(messagebean.toString());
        messagebean.execute();
    }

    @Test
    public void test2() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        MessageBean bean = ac.getBean("messagebean2", MessageBean.class);
        bean.execute();
    }
}
復制代碼

 

   

3. 執行Test2 有如下結果所示:

復制代碼
moduleName=資費管理
pageSize=5
username=andy
password=123
---List信息如下---
Tom
Andy
---Set信息如下---
James Gosling
Martin fowler
---Map信息如下---
1001=Java語言基礎
1002=Java Web基礎
---Properties信息如下---
password=1234
username=root
復制代碼

 

這個結果說明, 通過引用方式也可以為bean注入集合屬性.

步驟九:利用 Spring表達式注入屬性值

1.在工程的src下,新建屬性文件db.properties,文件內容如下:

    user=scott

2. 修改applicationContext.xml文件,注入Spring表達式值,代碼所示:

復制代碼
<!-- 加載properties文件為bean -->
 <util:properties id="jdbcProperties" location="classpath:db.properties" />
 
 
 <bean id="messagebean" class="org.tarena.bean.MessageBean">
 
  <!-- ================================================================ -->
 
  <property name="moduleName" value="資費管理"></property>
  <property name="pageSize" value="5"></property>
  <!-- 表達式注入 -->
  <property name="username" value="#{jdbcProperties.user}"></property>
 
  <property name="password">
   <null />
  </property>
復制代碼

 

3. 運行Test1類,控制台輸出結果所示:

復制代碼
org.springframework.context.support.ClassPathXmlApplicationContext@68861f24: startup date [Wed Jun 17 11:41:35 CST 2015]; root of context hierarchy
com.souvc.bean.MessageBean@209444d1
moduleName=測試基本屬性的注入
pageSize=5
username=daliu_it
password=123456
---List信息如下---
北京
上海
廣州
---Set信息如下---
James Gosling
Martin fowler
Larry Ellision
---Map信息如下---
1001=Java語言基礎
1002=Java Web基礎
1003=Spring使用基礎
---Properties信息如下---
password=1234
username=root
復制代碼

 

控制台輸出信息,說明獲取到了注入的Spring表達式值。

 

步驟十:注入null值

1. 修改applicationContext.xml文件,將屬性password注入null值,代碼如圖-11所示:

復制代碼
<?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:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">



    <!-- 加載properties文件為bean-->
    <util:properties id="jdbcProperties"
        location="classpath:db.properties" />


    <bean id="messagebean" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="測試基本屬性的注入"></property>
        <property name="pageSize" value="5"></property>
        <!-- 表達式注入 
            <property name="username" value="daliu_it"></property>-->
        <property name="username" value="#{jdbcProperties.user}"></property>
        <property name="password" >
        <null/>
        </property>
        <property name="someList">
            <list>
                <value>北京</value>
                <value>上海</value>
                <value>廣州</value>
            </list>
        </property>
        <property name="someSet">
            <set>
                <value>James Gosling</value>
                <value>Martin fowler</value>
                <value>Larry Ellision</value>
            </set>
        </property>
        <property name="someMap">
            <map>
                <entry key="1001" value="Java語言基礎"></entry>
                <entry key="1002" value="Java Web基礎"></entry>
                <entry key="1003" value="Spring使用基礎"></entry>
            </map>
        </property>
        <property name="someProps">
            <props>
                <prop key="username">root</prop>
                <prop key="password">1234</prop>
            </props>
        </property>
    </bean>


    <!-- 定義集合Bean -->
    <util:list id="oneList">
        <value>Tom</value>
        <value>Andy</value>
    </util:list>
    <util:set id="oneSet">
        <value>James Gosling</value>
        <value>Martin fowler</value>
    </util:set>
    <util:map id="oneMap">
        <entry key="1001" value="Java語言基礎"></entry>
        <entry key="1002" value="Java Web基礎"></entry>
    </util:map>
    <util:properties id="oneProps">
        <prop key="username">root</prop>
        <prop key="password">1234</prop>
    </util:properties>



    <!-- 引用方式注入集合屬性 -->
    <bean id="messagebean2" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="資費管理"></property>
        <property name="pageSize" value="5"></property>
        <property name="username" value="andy"></property>
        <property name="password" value="123"></property>

        <!-- 引用方式注入集合屬性 -->
        <property name="someList" ref="oneList" />
        <property name="someSet" ref="oneSet" />
        <property name="someMap" ref="oneMap" />
        <property name="someProps" ref="oneProps" />
    </bean>
</beans>
復制代碼

 


 

2. 運行Test1類,控制台輸出結果:

復制代碼
org.springframework.context.support.ClassPathXmlApplicationContext@2996c1b0: startup date [Wed Jun 17 11:42:47 CST 2015]; root of context hierarchy
com.souvc.bean.MessageBean@195ed659
moduleName=測試基本屬性的注入
pageSize=5
username=daliu_it
password=null
---List信息如下---
北京
上海
廣州
---Set信息如下---
James Gosling
Martin fowler
Larry Ellision
---Map信息如下---
1001=Java語言基礎
1002=Java Web基礎
1003=Spring使用基礎
---Properties信息如下---
password=1234
username=root
復制代碼

 

控制台輸出所示的信息,說明獲取到了注入的null值。

1.3 完整代碼

MessageBean類的完整代碼如下所示:

復制代碼
package com.souvc.bean;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MessageBean {
    private String moduleName;
    private int pageSize;
    private String username;
    private String password = "";

    private List<String> someList;
    private Set<String> someSet;
    private Map<String, Object> someMap;
    private Properties someProps;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getModuleName() {
        return moduleName;
    }

    public void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public List<String> getSomeList() {
        return someList;
    }

    public void setSomeList(List<String> someList) {
        this.someList = someList;
    }

    public Set<String> getSomeSet() {
        return someSet;
    }

    public void setSomeSet(Set<String> someSet) {
        this.someSet = someSet;
    }

    public Map<String, Object> getSomeMap() {
        return someMap;
    }

    public void setSomeMap(Map<String, Object> someMap) {
        this.someMap = someMap;
    }

    public Properties getSomeProps() {
        return someProps;
    }

    public void setSomeProps(Properties someProps) {
        this.someProps = someProps;
    }

    public String execute() {
        System.out.println("moduleName=" + moduleName);
        System.out.println("pageSize=" + pageSize);
        System.out.println("username=" + username);
        System.out.println("password=" + password);
        System.out.println("---List信息如下---");

        for (String s : someList) {
            System.out.println(s);
        }
        System.out.println("---Set信息如下---");
        for (String s : someSet) {
            System.out.println(s);
        }
        System.out.println("---Map信息如下---");
        Set<String> keys = someMap.keySet();
        for (String key : keys) {
            System.out.println(key + "=" + someMap.get(key));
        }
        System.out.println("---Properties信息如下---");
        Set<Object> keys1 = someProps.keySet();
        for (Object key : keys1) {
            System.out.println(key + "="
                    + someProps.getProperty(key.toString()));
        }

        return "success";
    }

}
復制代碼

 

Test1,Test2的完整代碼如下:

復制代碼
package com.souvc.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.souvc.bean.MessageBean;

public class TestCase {

    @Test
    public void test1() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        System.out.println(ac);

        MessageBean messagebean = ac.getBean("messagebean", MessageBean.class);
        System.out.println(messagebean.toString());
        messagebean.execute();
    }

    @Test
    public void test2() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        MessageBean bean = ac.getBean("messagebean2", MessageBean.class);
        bean.execute();
    }
}
復制代碼

 

applicationContext.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">



    <!-- 加載properties文件為bean-->
    <util:properties id="jdbcProperties"
        location="classpath:db.properties" />


    <bean id="messagebean" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="測試基本屬性的注入"></property>
        <property name="pageSize" value="5"></property>
        <!-- 表達式注入 
            <property name="username" value="daliu_it"></property>-->
        <property name="username" value="#{jdbcProperties.user}"></property>
        <property name="password" >
        <null/>
        </property>
        <property name="someList">
            <list>
                <value>北京</value>
                <value>上海</value>
                <value>廣州</value>
            </list>
        </property>
        <property name="someSet">
            <set>
                <value>James Gosling</value>
                <value>Martin fowler</value>
                <value>Larry Ellision</value>
            </set>
        </property>
        <property name="someMap">
            <map>
                <entry key="1001" value="Java語言基礎"></entry>
                <entry key="1002" value="Java Web基礎"></entry>
                <entry key="1003" value="Spring使用基礎"></entry>
            </map>
        </property>
        <property name="someProps">
            <props>
                <prop key="username">root</prop>
                <prop key="password">1234</prop>
            </props>
        </property>
    </bean>


    <!-- 定義集合Bean -->
    <util:list id="oneList">
        <value>Tom</value>
        <value>Andy</value>
    </util:list>
    <util:set id="oneSet">
        <value>James Gosling</value>
        <value>Martin fowler</value>
    </util:set>
    <util:map id="oneMap">
        <entry key="1001" value="Java語言基礎"></entry>
        <entry key="1002" value="Java Web基礎"></entry>
    </util:map>
    <util:properties id="oneProps">
        <prop key="username">root</prop>
        <prop key="password">1234</prop>
    </util:properties>



    <!-- 引用方式注入集合屬性 -->
    <bean id="messagebean2" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="資費管理"></property>
        <property name="pageSize" value="5"></property>
        <property name="username" value="andy"></property>
        <property name="password" value="123"></property>

        <!-- 引用方式注入集合屬性 -->
        <property name="someList" ref="oneList" />
        <property name="someSet" ref="oneSet" />
        <property name="someMap" ref="oneMap" />
        <property name="someProps" ref="oneProps" />
    </bean>
</beans>
復制代碼

 

源碼如下:http://yunpan.cn/cQVU3sLcMzXGC  訪問密碼 daf3

 

2 測試Spring自動組件掃描方式

2.1 問題

如何使用組件掃描的方式和"注解標記"配合獲取容器中的ExampleBean對象。

2.2 方案

使用組件掃描,首先需要在XML配置中指定掃描類路徑,配置代碼如下:

 

    <context:component-scan 
                  base-package="com.souvc"/> 

 

上述配置,容器實例化時會自動掃描com.souvc 包及其子包下所有組件類。

指定掃描類路徑後,並不是該路徑下所有組件類都掃描到Spring容器的,只有在組件類定義前面有以下注解標記時,才會掃描到Spring容器。


復制代碼
@Component  泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。

@Name 通用注解

@Service  業務層組件注解, 用於標注業務層組件

@Repository  持久層組件注解,用於標注數據訪問組件,即DAO組件

@Controller  控制層組件注解,用於標注控制層組件(如struts中的action)
復制代碼

 

2.3 步驟

步驟一:新建類ExampleBean

新建類ExampleBean,在該類前使用通用組件注解“@Component”,表明ExampleBean為可被掃描的組件,代碼如下所示:

復制代碼
package com.souvc.bean;

import org.springframework.stereotype.Component;

@Component
public class ExampleBean {

    public ExampleBean() {
        System.out.println("實例化ExampleBean");
    }

    public void execute() {
        System.out.println("執行ExampleBean處理");
    }
}
復制代碼

 

 

步驟二: 修改applicationContext.xml

修改applicationContext.xml,使容器實例化時自動掃描org.tarena包及其子包下所有組件類

 
<!-- 組件掃描 -->
    <context:component-scan base-package="com.souvc" />

 

步驟三: 新建方法Test3

 

復制代碼
@Test
    public void test3() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        ExampleBean bean = ac.getBean("exampleBean", ExampleBean.class);
        bean.execute();
    }
復制代碼

 

運行Test3方法,控制台輸出結果:


實例化ExampleBean
執行ExampleBean處理

 

控制台輸出上述結果,說明Spring會自動使用組件掃描的方式創建ExampleBean實例, 並且Test3中獲取到了這個ExampleBean對象。

2.4 完整代碼

ExampleBean類的完整代碼如下所示:

復制代碼
package com.souvc.bean;

import org.springframework.stereotype.Component;

@Component
public class ExampleBean {

    public ExampleBean() {
        System.out.println("實例化ExampleBean");
    }

    public void execute() {
        System.out.println("執行ExampleBean處理");
    }
}
復制代碼

 

TestCase 類的完整代碼如下所示:

復制代碼
package com.souvc.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.souvc.bean.ExampleBean;
import com.souvc.bean.MessageBean;

public class TestCase {

    @Test
    public void test1() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        System.out.println(ac);

        MessageBean messagebean = ac.getBean("messagebean", MessageBean.class);
        System.out.println(messagebean.toString());
        messagebean.execute();
    }

    @Test
    public void test2() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        MessageBean bean = ac.getBean("messagebean2", MessageBean.class);
        bean.execute();
    }

    @Test
    public void test3() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        ExampleBean bean = ac.getBean("exampleBean", ExampleBean.class);
        bean.execute();
    }
}
復制代碼

 

applicationContext.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">



    <!-- 加載properties文件為bean-->
    <util:properties id="jdbcProperties"
        location="classpath:db.properties" />


    <bean id="messagebean" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="測試基本屬性的注入"></property>
        <property name="pageSize" value="5"></property>
        <!-- 表達式注入 
            <property name="username" value="daliu_it"></property>-->
        <property name="username" value="#{jdbcProperties.user}"></property>
        <property name="password">
            <null />
        </property>
        <property name="someList">
            <list>
                <value>北京</value>
                <value>上海</value>
                <value>廣州</value>
            </list>
        </property>
        <property name="someSet">
            <set>
                <value>James Gosling</value>
                <value>Martin fowler</value>
                <value>Larry Ellision</value>
            </set>
        </property>
        <property name="someMap">
            <map>
                <entry key="1001" value="Java語言基礎"></entry>
                <entry key="1002" value="Java Web基礎"></entry>
                <entry key="1003" value="Spring使用基礎"></entry>
            </map>
        </property>
        <property name="someProps">
            <props>
                <prop key="username">root</prop>
                <prop key="password">1234</prop>
            </props>
        </property>
    </bean>


    <!-- 定義集合Bean -->
    <util:list id="oneList">
        <value>Tom</value>
        <value>Andy</value>
    </util:list>
    <util:set id="oneSet">
        <value>James Gosling</value>
        <value>Martin fowler</value>
    </util:set>
    <util:map id="oneMap">
        <entry key="1001" value="Java語言基礎"></entry>
        <entry key="1002" value="Java Web基礎"></entry>
    </util:map>
    <util:properties id="oneProps">
        <prop key="username">root</prop>
        <prop key="password">1234</prop>
    </util:properties>



    <!-- 引用方式注入集合屬性 -->
    <bean id="messagebean2" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="資費管理"></property>
        <property name="pageSize" value="5"></property>
        <property name="username" value="andy"></property>
        <property name="password" value="123"></property>

        <!-- 引用方式注入集合屬性 -->
        <property name="someList" ref="oneList" />
        <property name="someSet" ref="oneSet" />
        <property name="someMap" ref="oneMap" />
        <property name="someProps" ref="oneProps" />
    </bean>


    <!-- 組件掃描 -->
    <context:component-scan base-package="com.souvc" />


</beans>
復制代碼

 

 

3 如何控制ExampleBean實例化方式

3.1 問題

使用組件掃描的方式,重構如何控制ExampleBean實例化為單例或非單例模式。

3.2 方案

1. 通常受Spring管理的組件,默認的作用域是"singleton"。如果需要其他的作用域可以使用@Scope注解,只要在注解中提供作用域的名稱即可,代碼如下:

    @Component
    @Scope("singleton")
    public class ExampleBean {
       ...
        }

 

2. @PostConstruct和@PreDestroy注解標記分別用於指定初始化和銷毀回調方法,代碼如下:

復制代碼
    public class ExampleBean { 
          @PostConstruct 
          public void init() {
                //初始化回調方法
          } 
          
          @PreDestroy 
          public void destroy() { 
                 //銷毀回調方法
           }
     }
復制代碼

 

 

3.3 步驟

步驟一:Bean對象的創建模式

1. 修改ExampleBean,使用prototype模式創建 ExampleBean 對象,修改的代碼:

復制代碼
package com.souvc.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class ExampleBean {

    public ExampleBean() {
        System.out.println("實例化ExampleBean");
    }

//    public void execute() {
//        System.out.println("執行ExampleBean處理");
//    }
//
//    @PostConstruct
//    public void init() {
//        System.out.println("初始化ExampleBean對象");
//    }
//
//    @PreDestroy
//    public void destroy() {
//        System.out.println("銷毀ExampleBean對象");
//    }
}
復制代碼

 

2. 新建類Test4在該類中創建兩個ExampleBean對象,通過比較操作符==進行比較,代碼如圖-19所示:

復制代碼
    @Test
    public void test4() {
        String conf = "applicationContext.xml";
        AbstractApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class);
        ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class);
        System.out.println(bean1 == bean2);
        ac.close();
    }
復制代碼

 

3. 運行Test4,控制台輸出結果如下:

實例化ExampleBean
實例化ExampleBean
false

 

通過前面的講解,了解到默認情況下Spring容器是通過單例模式創建Bean對象的。通過本案例的運行結果,可以看出使用原型方式,調用了2次ExampleBean類的構造方法,說明創建了2個ExampleBean對象。

4. 如果想要使用單例模式創建對象,也可以使用注解的方式進行顯示標注,修改ExampleBean類的代碼所示:

復制代碼
package com.souvc.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
//@Scope("prototype")
@Scope("singleton")
public class ExampleBean {

    public ExampleBean() {
        System.out.println("實例化ExampleBean");
    }

//    public void execute() {
//        System.out.println("執行ExampleBean處理");
//    }
//
//    @PostConstruct
//    public void init() {
//        System.out.println("初始化ExampleBean對象");
//    }
//
//    @PreDestroy
//    public void destroy() {
//        System.out.println("銷毀ExampleBean對象");
//    }
}
復制代碼

 

5. 再次運行Test4,控制台輸出結果如下:

實例化ExampleBean
true
 

上述運行結果可以看得出,兩個ExampleBean對象,通過比較操作符“ ==”進行比較的輸出結果為true,說明Spring容器是通過單例模式創建Bean對象的。

步驟二:Bean對象的初始化和銷毀

1. 修改ExampleBean類,加入方法init和方法destroy,並使用注解“@PostConstruct”和注解“@PreDestroy”指定init為初始化的回調方法、destroy為銷毀的回調方法,代碼如下所示:

復制代碼
package com.souvc.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
//@Scope("prototype")
@Scope("singleton")
public class ExampleBean {

    public ExampleBean() {
        System.out.println("實例化ExampleBean");
    }

    public void execute() {
        System.out.println("執行ExampleBean處理");
    }

    @PostConstruct
    public void init() {
        System.out.println("初始化ExampleBean對象");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("銷毀ExampleBean對象");
    }
}
復制代碼

 

2.運行Test4類,控制台輸出結果所示:

復制代碼
實例化ExampleBean
初始化ExampleBean對象
true
2015-6-17 14:26:05 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@45b9ce4b: startup date [Wed Jun 17 14:26:04 CST 2015]; root of context hierarchy
2015-6-17 14:26:05 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@36f0b7f8: defining beans [jdbcProperties,messagebean,oneList,oneSet,oneMap,oneProps,messagebean2,exampleBean,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
銷毀ExampleBean對象
復制代碼

 

控制台輸出了“初始化ExampleBean對象”和“銷毀ExampleBean對象”,說明使用組件掃描的方式為ExampleBean類添加初始化和銷毀的回調方法成功。

3.4 完整代碼

ExampleBean類的完整代碼如下所示:

復制代碼
package com.souvc.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
//@Scope("prototype")
@Scope("singleton")
public class ExampleBean {

    public ExampleBean() {
        System.out.println("實例化ExampleBean");
    }

    public void execute() {
        System.out.println("執行ExampleBean處理");
    }

    @PostConstruct
    public void init() {
        System.out.println("初始化ExampleBean對象");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("銷毀ExampleBean對象");
    }
}
復制代碼

 

 

Test4類的完整代碼如下所示:

復制代碼
package com.souvc.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.souvc.bean.ExampleBean;
import com.souvc.bean.MessageBean;

public class TestCase {

    @Test
    public void test1() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        System.out.println(ac);

        MessageBean messagebean = ac.getBean("messagebean", MessageBean.class);
        System.out.println(messagebean.toString());
        messagebean.execute();
    }

    @Test
    public void test2() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        MessageBean bean = ac.getBean("messagebean2", MessageBean.class);
        bean.execute();
    }

    @Test
    public void test3() {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        ExampleBean bean = ac.getBean("exampleBean", ExampleBean.class);
        //bean.execute();
    }

    @Test
    public void test4() {
        String conf = "applicationContext.xml";
        AbstractApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class);
        ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class);
        System.out.println(bean1 == bean2);
        ac.close();
    }

}
復制代碼

 

applicationContext.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">



    <!-- 加載properties文件為bean-->
    <util:properties id="jdbcProperties"
        location="classpath:db.properties" />


    <bean id="messagebean" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="測試基本屬性的注入"></property>
        <property name="pageSize" value="5"></property>
        <!-- 表達式注入 
            <property name="username" value="daliu_it"></property>-->
        <property name="username" value="#{jdbcProperties.user}"></property>
        <property name="password">
            <null />
        </property>
        <property name="someList">
            <list>
                <value>北京</value>
                <value>上海</value>
                <value>廣州</value>
            </list>
        </property>
        <property name="someSet">
            <set>
                <value>James Gosling</value>
                <value>Martin fowler</value>
                <value>Larry Ellision</value>
            </set>
        </property>
        <property name="someMap">
            <map>
                <entry key="1001" value="Java語言基礎"></entry>
                <entry key="1002" value="Java Web基礎"></entry>
                <entry key="1003" value="Spring使用基礎"></entry>
            </map>
        </property>
        <property name="someProps">
            <props>
                <prop key="username">root</prop>
                <prop key="password">1234</prop>
            </props>
        </property>
    </bean>


    <!-- 定義集合Bean -->
    <util:list id="oneList">
        <value>Tom</value>
        <value>Andy</value>
    </util:list>
    <util:set id="oneSet">
        <value>James Gosling</value>
        <value>Martin fowler</value>
    </util:set>
    <util:map id="oneMap">
        <entry key="1001" value="Java語言基礎"></entry>
        <entry key="1002" value="Java Web基礎"></entry>
    </util:map>
    <util:properties id="oneProps">
        <prop key="username">root</prop>
        <prop key="password">1234</prop>
    </util:properties>



    <!-- 引用方式注入集合屬性 -->
    <bean id="messagebean2" class="com.souvc.bean.MessageBean">
        <property name="moduleName" value="資費管理"></property>
        <property name="pageSize" value="5"></property>
        <property name="username" value="andy"></property>
        <property name="password" value="123"></property>

        <!-- 引用方式注入集合屬性 -->
        <property name="someList" ref="oneList" />
        <property name="someSet" ref="oneSet" />
        <property name="someMap" ref="oneMap" />
        <property name="someProps" ref="oneProps" />
    </bean>


    <!-- 組件掃描 -->
    <context:component-scan base-package="com.souvc" />


</beans>
復制代碼

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved