国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

Spring學習筆記之 Spring IOC容器(一)

2019-11-15 00:36:20
字體:
來源:轉載
供稿:網(wǎng)友
SPRing學習筆記之 Spring IOC容器(一)

本節(jié)主要內(nèi)容: 1.實例化Spring容器示例 2.利用Spring容器創(chuàng)建javaBean對象 3.如何控制Bean實例化 4.利用Spring實現(xiàn)bean屬性setter方式注入 5.利用構造器參數(shù)實現(xiàn)依賴屬性的注入 6.利用Spring的自動裝配功能實現(xiàn)自動屬性注入

1 實例化Spring容器示例1.1 問題

使用applicationContext的方式實例化Spring容器。

1.2 方案

使用ApplicationContext的方式實例化Spring容器的核心代碼如下:

    String conf = "applicationContext.xml";    ApplicationContext ac =              new ClassPathXmlApplicationContext(conf);

1.3 步驟

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

新建名為 SouvcSpring 的web工程,在該工程導入5個Spring相關jar包。

commons-logging.jarspring-core.jarspring-context.jarspring-beans.jarspring-expression.jar

網(wǎng)盤下載jar包 :http://yunpan.cn/cQJhPMPRZeLH7 訪問密碼 2bf8

步驟二:新建Spring配置文件

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

<?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>

步驟三:新建類Test1

導入JUnit4 , 用于軟件的單元測試.

新建類TestCase,在類中使用ApplicationContext的方式實例化Spring容器。

在TestCase類中添加測試方法testInitContext():

/** 測試實例化Spring容器示例 */    @Test    public void testInitContext() {        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        System.out.println(ac);    }

步驟四:運行testInitContext()方法

運行testInitContext()方法,控制臺輸出結果

org.springframework.context.support.ClassPathXmlApplicationContext@5a77a7f9: startup date [Tue Jun 16 17:22:35 CST 2015]; root of context hierarchy

控制臺輸出以上的信息,說明實例化Spring容器成功。

1.4 完整代碼

TestCase類的完整代碼如下:

package com.souvc.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestCase {    /** 測試實例化Spring容器示例 */    @Test    public void testInitContext() {        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        System.out.println(ac);    }}

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>

2 利用Spring容器創(chuàng)建JavaBean對象2.1 問題

測試Spring支持的多種JavaBean對象創(chuàng)建方式:

1. 用構造器來實例化的方式。

利用Spring調用構造器 GregorianCalendar 創(chuàng)建 Calendar實例.

2. 使用靜態(tài)工廠方法實例化的方式。

利用Spring調用 Calendar 的靜態(tài)工廠方法getInstance() 創(chuàng)建 Calendar實例.

3. 使用實例工廠方法實例化的方式。

利用Spring創(chuàng)建 GregorianCalendar 對象作為工廠, 調用getTime()方法創(chuàng)建Date類型對象實例.

2.2 方案

1. 用構造器來實例化的方式的配置代碼如下:

<bean id="calendarObj1" class="java.util.GregorianCalendar"></bean>

bean標記中id屬性calendarObj1用于定義bean名字, 是程序代碼中獲得Spring管理bean對象的標識, 這個名字不能重復, class用于指定創(chuàng)建對象的類GregorianCalendar, Spring會自動的調用GregorianCalendar類的默認構造器創(chuàng)建bean對象實例.

2. 使用靜態(tài)工廠方法實例化的方式的配置代碼如下:

    <bean id="calendarObj2"     class="java.util.Calendar" factory-method="getInstance">        </bean>

bean標記中id屬性calendarObj2用于定義bean名字, 是程序代碼中獲得Spring管理bean對象的標識, 這個名字不能重復, class屬性用于指定創(chuàng)建對象的工廠類Calendar, factory-method屬性用于指定創(chuàng)建對象的靜態(tài)工廠方法getInstance, Spring會自動的調用工廠類Calendar靜態(tài)工廠方法getInstance創(chuàng)建bean對象實例.

3. 使用實例工廠方法實例化的方式的配置代碼如下:

 <bean id="calendarObj3" class="java.util.GregorianCalendar"></bean>    <bean id="dateObj" factory-bean="calendarObj3" factory-method="getTime">    </bean>

這里定義了兩個bean, 其中一個bean calendarObj3是用于創(chuàng)建 dateObj 對象的實例工廠.

另外一個bean標記中id屬性dateObj用于定義bean名字, 是程序代碼中獲得Spring管理bean對象的標識, 這個名字不能重復, factory-bean屬性用于指定創(chuàng)建對象的工廠對象calendarObj3, 前面定義的一個bean, factory-method屬性用于指定創(chuàng)建對象的工廠方法getTime, Spring會自動的調用工廠類Calendar靜態(tài)工廠方法getInstance創(chuàng)建bean對象實例.

2.3 步驟

步驟一:配置 applicationContext.xml, 增加Bean對象創(chuàng)建聲明

代碼如下所示:

<!--  1. 用構造器來實例化的方式的配置代碼如下: -->    <bean id="calendarObj1" class="java.util.GregorianCalendar"></bean>    <!-- 2. 使用靜態(tài)工廠方法實例化的方式的配置代碼如下:  -->    <bean id="calendarObj2" class="java.util.Calendar"        factory-method="getInstance">    </bean>    <!-- 3. 使用實例工廠方法實例化的方式的配置代碼如下:  -->    <bean id="calendarObj3" class="java.util.GregorianCalendar"></bean>    <bean id="dateObj" factory-bean="calendarObj3"        factory-method="getTime">    </bean>

步驟二:在TestCase類中增加測試方法testCreateBeanObject,測試Spring創(chuàng)建對象的結果

先創(chuàng)建Spring容器對象, 再調用getBean方法獲得Spring創(chuàng)建的對象實例,并且利用輸出語句測試對象是否存在. 這個代碼中要注意: getBean方法的參數(shù)必須是上一個步驟中定義的bean標記上的id屬性的值, 否則會出現(xiàn)運行異常.

代碼如下所示:

/** 測試Spring支持的多種JavaBean對象創(chuàng)建方式 */    @Test    public void testCreateBeanObject() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 1. 用構造器來實例化的方式。        // 利用Spring調用構造器 GregorianCalendar 創(chuàng)建 Calendar實例.        // Calendar cal1 = (Calendar)ac.getBean("calendarObj1"); //方式1        Calendar cal1 = ac.getBean("calendarObj1", Calendar.class); // 方式2        System.out.println("cal1:" + cal1);        // 2. 使用靜態(tài)工廠方法實例化的方式。        // 利用Spring調用 Calendar 的靜態(tài)工廠方法getInstance() 創(chuàng)建 Calendar實例.        Calendar cal2 = ac.getBean("calendarObj2", Calendar.class);        System.out.println("cal2:" + cal2);        // 3. 使用實例工廠方法實例化的方式。        // 利用Spring創(chuàng)建 GregorianCalendar 對象作為工廠, 調用getTime()方法創(chuàng)建Date類型對象實例.        Date date = ac.getBean("dateObj", Date.class);        System.out.println("date:" + date);    }

步驟三:運行測試方法測試bean實例化

控制臺輸出結果如下所示:

cal1:java.util.GregorianCalendar[time=1434446926808,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=5,WEEK_OF_YEAR=25,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=167,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=5,HOUR_OF_DAY=17,MINUTE=28,SECOND=46,MILLISECOND=808,ZONE_OFFSET=28800000,DST_OFFSET=0]cal2:java.util.GregorianCalendar[time=1434446926837,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=5,WEEK_OF_YEAR=25,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=167,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=5,HOUR_OF_DAY=17,MINUTE=28,SECOND=46,MILLISECOND=837,ZONE_OFFSET=28800000,DST_OFFSET=0]date:Tue Jun 16 17:28:46 CST 2015

2.4 完整代碼

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

package com.souvc.test;import java.util.Calendar;import java.util.Date;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestCase {    /** 測試實例化Spring容器示例 */    @Test    public void testInitContext() {        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        System.out.println(ac);    }    /** 測試Spring支持的多種JavaBean對象創(chuàng)建方式 */    @Test    public void testCreateBeanObject() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 1. 用構造器來實例化的方式。        // 利用Spring調用構造器 GregorianCalendar 創(chuàng)建 Calendar實例.        // Calendar cal1 = (Calendar)ac.getBean("calendarObj1"); //方式1        Calendar cal1 = ac.getBean("calendarObj1", Calendar.class); // 方式2        System.out.println("cal1:" + cal1);        // 2. 使用靜態(tài)工廠方法實例化的方式。        // 利用Spring調用 Calendar 的靜態(tài)工廠方法getInstance() 創(chuàng)建 Calendar實例.        Calendar cal2 = ac.getBean("calendarObj2", Calendar.class);        System.out.println("cal2:" + cal2);        // 3. 使用實例工廠方法實例化的方式。        // 利用Spring創(chuàng)建 GregorianCalendar 對象作為工廠, 調用getTime()方法創(chuàng)建Date類型對象實例.        Date date = ac.getBean("dateObj", Date.class);        System.out.println("date:" + date);    }}

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">    <!--  1. 用構造器來實例化的方式的配置代碼如下: -->    <bean id="calendarObj1" class="java.util.GregorianCalendar"></bean>    <!-- 2. 使用靜態(tài)工廠方法實例化的方式的配置代碼如下:  -->    <bean id="calendarObj2" class="java.util.Calendar"        factory-method="getInstance">    </bean>    <!-- 3. 使用實例工廠方法實例化的方式的配置代碼如下:  -->    <bean id="calendarObj3" class="java.util.GregorianCalendar"></bean>    <bean id="dateObj" factory-bean="calendarObj3"        factory-method="getTime">    </bean></beans>

3 如何控制Bean實例化3.1 問題

測試Bean的作用域、Bean的生命周期回調、Bean對象的創(chuàng)建時機以及如何指定bean依賴關系。

3.2 步驟

步驟一:Bean對象的創(chuàng)建模式

1. 新建包com.souvc.dao , 新建類 ExampleBean。

package com.souvc.dao;public class ExampleBean {    public ExampleBean() {        System.out.println("實例化ExampleBean");    }    public void execute() {        System.out.println("執(zhí)行ExampleBean處理");    }    }

2. 在applicationContext.xml文件中,配置ExampleBean,代碼如圖-9所示:

<bean id="exampleBean" class="com.souvc.dao.ExampleBean"></bean>

3. 在TestCase中新建測試方法testExampleBean(),在方法中從Spring中獲取兩個ExampleBean類型對象,通過比較操作 符“ == ” 進行比較,如果輸出結果為true,則表明兩次獲取的是同一個對象,即創(chuàng)建對象的方式單例模式,代碼如圖-10所示:

@Test    public void testExampleBean() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 獲取ExampleBean對象        ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class);        ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class);        System.out.println(bean1 == bean2);                        // 關閉Spring容器, 注意AbstractApplicationContext類型定義了 close()方法        //AbstractApplicationContext ctx = (AbstractApplicationContext) ac;        //ctx.close();    }

4. 運行testExampleBean()方法,控制臺輸出結果如下:

  1. 實例化ExampleBean
  2. true

上述運行結果可以看得出在軟件運行期間ExampleBean的構造器只被調用過一次, 創(chuàng)建過一個對象,兩次獲得引用變量bean1, bean2,通過比較操作符“ ==” 進行比較的輸出結果為true, 說明是引用了同一個對象, 也就說明Spring容器創(chuàng)建Bean對象是唯一實例, 是單例對象。

5. 修改applicationContext.xml,設置創(chuàng)建Bean的模式為原型模式(prototype)

<!-- scope="singleton" 模式     <bean id="exampleBean" class="com.souvc.dao.ExampleBean" scope="singleton"></bean>--><!-- scope="prototype" 模式 -->    <bean id="exampleBean" class="com.souvc.dao.ExampleBean" scope="prototype"></bean>

6. 再次運行testExampleBean()方法,控制臺輸出結果如下:

  1. 實例化ExampleBean
  2. 實例化ExampleBean
  3. false

這個結果說明調用了2次ExampleBean類的構造方法創(chuàng)建了兩個Bean對象,比較結果是false表示bean1和bean2引用了這兩個不同的對象, 這樣創(chuàng)建bean就不再是單例模式了。

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

1. 修改ExampleBean類,加入方法init和方法destroy,代碼如下所示:

package com.souvc.dao;public class ExampleBean {    public ExampleBean() {        System.out.println("實例化ExampleBean");    }    public void execute() {        System.out.println("執(zhí)行ExampleBean處理");    }    public void init() {        System.out.println("初始化ExampleBean對象");    }    public void destroy() {        System.out.println("銷毀ExampleBean對象");    }}

2. 修改applicationContext.xml,希望在bean對象創(chuàng)建后自動調用init()方法,代碼如圖-12所示:

<!-- scope="prototype" 模式 -->    <bean id="exampleBean" class="com.souvc.dao.ExampleBean"        scope="prototype" init-method="init">    </bean>

3.運行testExampleBean()方法,自定義的初始化的方法在對象被創(chuàng)建后調用,如圖-13所示:

實例化ExampleBean初始化ExampleBean對象實例化ExampleBean初始化ExampleBean對象false

4.修改applicationContext.xml,希望在bean對象銷毀前自動調用destroy方法,bean對象在spring容器關閉的時候被銷毀,代碼如圖-14所示:

<!-- scope="prototype" 模式 -->    <bean id="exampleBean" class="com.souvc.dao.ExampleBean"        scope="prototype" init-method="init"  destroy-method="destroy">    </bean>

5.修改testExampleBean()方法,關閉ApplicationContext對象,代碼如圖-15所示:

@Test    public void testExampleBean() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 獲取ExampleBean對象        ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class);        ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class);        System.out.println(bean1 == bean2);                        // 關閉Spring容器, 注意AbstractApplicationContext類型定義了 close()方法        AbstractApplicationContext ctx = (AbstractApplicationContext) ac;        ctx.close();    }

6.運行testExampleBean()方法,控制臺輸出結果如圖

控制臺沒有輸出預期的“銷毀ExampleBean對象”的結果。原因在于applicationContext.xml文件中設置的destroy-method屬性僅僅對單例模式起作用,在prototype模式下沒有意義。

7.修改applicationContext.xml,使用singleton模式創(chuàng)建Bean對象,代碼如圖-17所示:

<!-- scope="prototype" 模式 -->    <bean id="exampleBean" class="com.souvc.dao.ExampleBean"        scope="singleton" init-method="init"  destroy-method="destroy">    </bean>

8.運行testExampleBean()方法,控制臺輸出了“銷毀ExampleBean對象”,如圖-18所示:

9.在頂級的<beans/>元素中的default-init-method屬性以及default-destroy-method屬性,可以為容器所有<bean>指定初始化回調方法以及指定銷毀回調方法,代碼如圖-19所示:

<?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"    default-init-method="init" default-destroy-method="destroy" >

步驟三:Bean對象的創(chuàng)建時機

1. 注釋testExampleBean中如圖所示的代碼。

    @Test    public void testExampleBean() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 獲取ExampleBean對象        //ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class);        //ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class);        //System.out.println(bean1 == bean2);                        // 關閉Spring容器, 注意AbstractApplicationContext類型定義了 close()方法        //AbstractApplicationContext ctx = (AbstractApplicationContext) ac;        //ctx.close();    }

2. 運行testExampleBean方法,控制臺輸出結果

實例化ExampleBean初始化ExampleBean對象

控制臺打印結果,說明默認情況下ExampleBean在Spring容器被創(chuàng)建時就會創(chuàng)建。

3. 修改applicationContext.xml,通過設置配置文件屬性lazy-init="true",可以改變Spring容器創(chuàng)建對象的時機,代碼如圖-22所示:

<!-- scope="prototype" 模式 -->    <bean id="exampleBean" class="com.souvc.dao.ExampleBean"        scope="singleton" init-method="init" destroy-method="destroy" lazy-init="true">    </bean>

4.運行testExampleBean方法,控制臺沒有輸出信息,因為對象并沒有被實例化,或者說,實例化被延遲了。

5. 去除 testExampleBean方法注釋掉的代碼,

@Test    public void testExampleBean() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 獲取ExampleBean對象        ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class);        ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class);        System.out.println(bean1 == bean2);                        // 關閉Spring容器, 注意AbstractApplicationContext類型定義了 close()方法        AbstractApplicationContext ctx = (AbstractApplicationContext) ac;        ctx.close();    }

6.運行testExampleBean方法

從輸出結果可以看出,當使用ExampleBean對象時,才被創(chuàng)建,即,設置lazy-init="true"屬性后,對象不使用不創(chuàng)建。

7.在頂級的<beans/>元素中的default-lazy-init屬性,可以為容器所有<bean>指定延遲實例化特性

<?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"    default-init-method="init" default-destroy-method="destroy" default-lazy-init="true">

步驟四:指定bean依賴關系

1. 新建類ExampleBean1,代碼如下所示:

package com.souvc.dao;public class ExampleBean1 {    public ExampleBean1() {        System.out.println("實例化ExampleBean1");    }}

2. 修改applicationContext.xml文件,將ExampleBean依賴ExampleBean1

<!-- scope="prototype" 模式 -->    <bean id="exampleBean" class="com.souvc.dao.ExampleBean"        scope="singleton" init-method="init" destroy-method="destroy"        lazy-init="true" depends-on="exampleBean1">    </bean>    <!-- scope="prototype" 模式 -->    <bean id="exampleBean1" class="com.souvc.dao.ExampleBean1"        lazy-init="true">    </bean>

3. 運行testExampleBean方法,控制臺輸出結果如圖-27所示:

實例化ExampleBean1實例化ExampleBean初始化ExampleBean對象true2015-6-16 18:02:00 org.springframework.context.support.AbstractApplicationContext doClose信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@2996c1b0: startup date [Tue Jun 16 18:02:00 CST 2015]; root of context hierarchy2015-6-16 18:02:00 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@783c342b: defining beans [calendarObj1,calendarObj2,calendarObj3,dateObj,exampleBean,exampleBean1]; root of factory hierarchy銷毀ExampleBean對象

可以看出,由于ExampleBean依賴于ExampleBean1,因此在創(chuàng)建ExampleBean的同時,也創(chuàng)建了ExampleBean1。3.3 完整代碼

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

package com.souvc.dao;public class ExampleBean {    public ExampleBean() {        System.out.println("實例化ExampleBean");    }    public void execute() {        System.out.println("執(zhí)行ExampleBean處理");    }    public void init() {        System.out.println("初始化ExampleBean對象");    }    public void destroy() {        System.out.println("銷毀ExampleBean對象");    }}

ExampleBean1 源碼:

package com.souvc.dao;public class ExampleBean1 {    public ExampleBean1() {        System.out.println("實例化ExampleBean1");    }}

TestCase 源碼:

package com.souvc.test;import java.util.Calendar;import java.util.Date;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.souvc.dao.ExampleBean;public class TestCase {    /** 測試實例化Spring容器示例 */    @Test    public void testInitContext() {        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        System.out.println(ac);    }    /** 測試Spring支持的多種JavaBean對象創(chuàng)建方式 */    @Test    public void testCreateBeanObject() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 1. 用構造器來實例化的方式。        // 利用Spring調用構造器 GregorianCalendar 創(chuàng)建 Calendar實例.        // Calendar cal1 = (Calendar)ac.getBean("calendarObj1"); //方式1        Calendar cal1 = ac.getBean("calendarObj1", Calendar.class); // 方式2        System.out.println("cal1:" + cal1);        // 2. 使用靜態(tài)工廠方法實例化的方式。        // 利用Spring調用 Calendar 的靜態(tài)工廠方法getInstance() 創(chuàng)建 Calendar實例.        Calendar cal2 = ac.getBean("calendarObj2", Calendar.class);        System.out.println("cal2:" + cal2);        // 3. 使用實例工廠方法實例化的方式。        // 利用Spring創(chuàng)建 GregorianCalendar 對象作為工廠, 調用getTime()方法創(chuàng)建Date類型對象實例.        Date date = ac.getBean("dateObj", Date.class);        System.out.println("date:" + date);    }    @Test    public void testExampleBean() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 獲取ExampleBean對象        ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class);        ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class);        System.out.println(bean1 == bean2);                        // 關閉Spring容器, 注意AbstractApplicationContext類型定義了 close()方法        AbstractApplicationContext ctx = (AbstractApplicationContext) ac;        ctx.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"    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"    default-init-method="init" default-destroy-method="destroy"    default-lazy-init="true">    <!--  1. 用構造器來實例化的方式的配置代碼如下: -->    <bean id="calendarObj1" class="java.util.GregorianCalendar"></bean>    <!-- 2. 使用靜態(tài)工廠方法實例化的方式的配置代碼如下:  -->    <bean id="calendarObj2" class="java.util.Calendar"        factory-method="getInstance">    </bean>    <!-- 3. 使用實例工廠方法實例化的方式的配置代碼如下:  -->    <bean id="calendarObj3" class="java.util.GregorianCalendar"></bean>    <bean id="dateObj" factory-bean="calendarObj3"        factory-method="getTime">    </bean>    <!-- scope="singleton" 模式         <bean id="exampleBean" class="com.souvc.dao.ExampleBean" scope="singleton"></bean>-->    <!-- scope="prototype" 模式 -->    <bean id="exampleBean" class="com.souvc.dao.ExampleBean"        scope="singleton" init-method="init" destroy-method="destroy"        lazy-init="true" depends-on="exampleBean1">    </bean>    <!-- scope="prototype" 模式 -->    <bean id="exampleBean1" class="com.souvc.dao.ExampleBean1"        lazy-init="true">    </bean></beans>

4 利用Spring實現(xiàn)bean屬性setter方式注入4.1 問題

JDBCDataSource類封裝了管理數(shù)據(jù)庫連接的方法getConnection(), 這個方法在執(zhí)行之前需要數(shù)據(jù)庫連接參數(shù): 數(shù)據(jù)庫驅動, 連接URL, 用戶名和密碼.

JDBCDataSource代碼如下:

package com.souvc.dao;import java.io.Serializable;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class JDBCDataSource implements Serializable {    private String driver;    private String url;    private String user;    private String pwd;    public String getDriver() {        return driver;    }    public void setDriver(String driver) {        try {            // 注冊數(shù)據(jù)庫驅動            Class.forName(driver);            this.driver = driver;        } catch (Exception e) {            throw new RuntimeException(e);        }    }    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getUser() {        return user;    }    public void setUser(String user) {        this.user = user;    }    public String getPwd() {        return pwd;    }    public void setPwd(String pwd) {        this.pwd = pwd;    }    public Connection getConnection() throws SQLException {        Connection conn = DriverManager.getConnection(url, user, pwd);        return conn;    }    public void close(Connection conn) {        if (conn != null) {            try {                conn.close();            } catch (SQLException e) {                e.printStackTrace();            }        }    }}

利用Spring實現(xiàn)JDBCDataSource對象的創(chuàng)建, 再使用setter注入的方式將數(shù)據(jù)庫連接參數(shù)注入給JDBCDataSource。這樣就可以正常的調用getConnection()方法獲得數(shù)據(jù)庫連接了.

4.2 方案

利用Spring配置文件applicationContext.xml配置bean, 并且setter參數(shù)注入JDBCDataSource的連接參數(shù), 這樣Spring在創(chuàng)建JDBCDataSource對象以后就會自動化的調用setter方法注入數(shù)據(jù)庫連接參數(shù).

applicationContext.xml配置bean參考代碼如下:

<!-- setter注入  Oracle         <bean id="dataSource" class="com.souvc.dao.JDBCDataSource">        <property name="driver" value="oracle.jdbc.OracleDriver"></property>        <property name="url"        value="jdbc:oracle:thin:@localhost:1521:ora1">        </property>        <property name="user" value="root"></property>        <property name="pwd" value="123456"></property>        </bean>    -->    <!-- setter注入 MySQL -->    <bean id="dataSource" class="com.souvc.dao.JDBCDataSource">        <property name="driver" value="com.mysql.jdbc.Driver"></property>        <property name="url" value="jdbc:mysql://localhost:3306/csdn">        </property>        <property name="user" value="root"></property>        <property name="pwd" value="123456"></property>    </bean>

以上的源碼如下: http://yunpan.cn/cQVM3ZYbpZzrV 訪問密碼 42ea4.3 步驟

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

新建名為SouvcSpringIoC的web工程,在該工程導入如下面所示的6個jar包, 包括Spring API 和 Oracle JDBC Driver或者mysql JDBC DRIVER。

commons-logging.jarspring-core.jarspring-context.jarspring-beans.jarspring-expression.jarmysql-connector-java-5.1.7-bin.jar

ojdbc5.jar

步驟二:創(chuàng)建被Spring管理的JDBCDataScorce類, 用于連接到數(shù)據(jù)庫

代碼如下所示:

package com.souvc.dao;import java.io.Serializable;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class JDBCDataSource implements Serializable {    private String driver;    private String url;    private String user;    private String pwd;    public String getDriver() {        return driver;    }    public void setDriver(String driver) {        try {            // 注冊數(shù)據(jù)庫驅動            Class.forName(driver);            this.driver = driver;        } catch (Exception e) {            throw new RuntimeException(e);        }    }    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getUser() {        return user;    }    public void setUser(String user) {        this.user = user;    }    public String getPwd() {        return pwd;    }
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 张家口市| 福清市| 兴化市| 宝兴县| 汝州市| 永州市| 礼泉县| 库伦旗| 炉霍县| 五常市| 沾化县| 温泉县| 渝北区| 巴彦淖尔市| 建阳市| 民县| 大同市| 巴林右旗| 铜梁县| 特克斯县| 夹江县| 雷波县| 崇明县| 临潭县| 浦城县| 福建省| 金门县| 礼泉县| 宁南县| 宝应县| 洮南市| 济源市| 曲水县| 沿河| 乐都县| 太康县| 昭平县| 疏勒县| 青田县| 博爱县| 丹棱县|