亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 學院 > 開發設計 > 正文

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

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

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

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

網盤下載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容器創建JavaBean對象2.1 問題

測試Spring支持的多種JavaBean對象創建方式:

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

利用Spring調用構造器 GregorianCalendar 創建 Calendar實例.

2. 使用靜態工廠方法實例化的方式。

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

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

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

2.2 方案

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

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

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

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

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

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

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

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

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

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

2.3 步驟

步驟一:配置 applicationContext.xml, 增加Bean對象創建聲明

代碼如下所示:

<!--  1. 用構造器來實例化的方式的配置代碼如下: -->    <bean id="calendarObj1" class="java.util.GregorianCalendar"></bean>    <!-- 2. 使用靜態工廠方法實例化的方式的配置代碼如下:  -->    <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創建對象的結果

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

代碼如下所示:

/** 測試Spring支持的多種JavaBean對象創建方式 */    @Test    public void testCreateBeanObject() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 1. 用構造器來實例化的方式。        // 利用Spring調用構造器 GregorianCalendar 創建 Calendar實例.        // Calendar cal1 = (Calendar)ac.getBean("calendarObj1"); //方式1        Calendar cal1 = ac.getBean("calendarObj1", Calendar.class); // 方式2        System.out.println("cal1:" + cal1);        // 2. 使用靜態工廠方法實例化的方式。        // 利用Spring調用 Calendar 的靜態工廠方法getInstance() 創建 Calendar實例.        Calendar cal2 = ac.getBean("calendarObj2", Calendar.class);        System.out.println("cal2:" + cal2);        // 3. 使用實例工廠方法實例化的方式。        // 利用Spring創建 GregorianCalendar 對象作為工廠, 調用getTime()方法創建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對象創建方式 */    @Test    public void testCreateBeanObject() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 1. 用構造器來實例化的方式。        // 利用Spring調用構造器 GregorianCalendar 創建 Calendar實例.        // Calendar cal1 = (Calendar)ac.getBean("calendarObj1"); //方式1        Calendar cal1 = ac.getBean("calendarObj1", Calendar.class); // 方式2        System.out.println("cal1:" + cal1);        // 2. 使用靜態工廠方法實例化的方式。        // 利用Spring調用 Calendar 的靜態工廠方法getInstance() 創建 Calendar實例.        Calendar cal2 = ac.getBean("calendarObj2", Calendar.class);        System.out.println("cal2:" + cal2);        // 3. 使用實例工廠方法實例化的方式。        // 利用Spring創建 GregorianCalendar 對象作為工廠, 調用getTime()方法創建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. 使用靜態工廠方法實例化的方式的配置代碼如下:  -->    <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對象的創建時機以及如何指定bean依賴關系。

3.2 步驟

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

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

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

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

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

3. 在TestCase中新建測試方法testExampleBean(),在方法中從Spring中獲取兩個ExampleBean類型對象,通過比較操作 符“ == ” 進行比較,如果輸出結果為true,則表明兩次獲取的是同一個對象,即創建對象的方式單例模式,代碼如圖-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的構造器只被調用過一次, 創建過一個對象,兩次獲得引用變量bean1, bean2,通過比較操作符“ ==” 進行比較的輸出結果為true, 說明是引用了同一個對象, 也就說明Spring容器創建Bean對象是唯一實例, 是單例對象。

5. 修改applicationContext.xml,設置創建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類的構造方法創建了兩個Bean對象,比較結果是false表示bean1和bean2引用了這兩個不同的對象, 這樣創建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("執行ExampleBean處理");    }    public void init() {        System.out.println("初始化ExampleBean對象");    }    public void destroy() {        System.out.println("銷毀ExampleBean對象");    }}

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

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

3.運行testExampleBean()方法,自定義的初始化的方法在對象被創建后調用,如圖-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模式創建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對象的創建時機

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容器被創建時就會創建。

3. 修改applicationContext.xml,通過設置配置文件屬性lazy-init="true",可以改變Spring容器創建對象的時機,代碼如圖-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對象時,才被創建,即,設置lazy-init="true"屬性后,對象不使用不創建。

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,因此在創建ExampleBean的同時,也創建了ExampleBean1。3.3 完整代碼

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

package com.souvc.dao;public class ExampleBean {    public ExampleBean() {        System.out.println("實例化ExampleBean");    }    public void execute() {        System.out.println("執行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對象創建方式 */    @Test    public void testCreateBeanObject() {        // 實例化Spring容器示例        String conf = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);        // 1. 用構造器來實例化的方式。        // 利用Spring調用構造器 GregorianCalendar 創建 Calendar實例.        // Calendar cal1 = (Calendar)ac.getBean("calendarObj1"); //方式1        Calendar cal1 = ac.getBean("calendarObj1", Calendar.class); // 方式2        System.out.println("cal1:" + cal1);        // 2. 使用靜態工廠方法實例化的方式。        // 利用Spring調用 Calendar 的靜態工廠方法getInstance() 創建 Calendar實例.        Calendar cal2 = ac.getBean("calendarObj2", Calendar.class);        System.out.println("cal2:" + cal2);        // 3. 使用實例工廠方法實例化的方式。        // 利用Spring創建 GregorianCalendar 對象作為工廠, 調用getTime()方法創建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. 使用靜態工廠方法實例化的方式的配置代碼如下:  -->    <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實現bean屬性setter方式注入4.1 問題

JDBCDataSource類封裝了管理數據庫連接的方法getConnection(), 這個方法在執行之前需要數據庫連接參數: 數據庫驅動, 連接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 {            // 注冊數據庫驅動            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實現JDBCDataSource對象的創建, 再使用setter注入的方式將數據庫連接參數注入給JDBCDataSource。這樣就可以正常的調用getConnection()方法獲得數據庫連接了.

4.2 方案

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

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

步驟二:創建被Spring管理的JDBCDataScorce類, 用于連接到數據庫

代碼如下所示:

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 {            // 注冊數據庫驅動            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;    }
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
精品亚洲va在线va天堂资源站| 成人激情视频在线| 国产亚洲美女精品久久久| 日韩精品视频免费专区在线播放| 中文字幕久精品免费视频| 另类少妇人与禽zozz0性伦| 午夜免费在线观看精品视频| 亚洲欧美中文另类| 国产精品视频1区| 国产日韩在线看| 97热在线精品视频在线观看| 国产精品视频久久久| 国产精品黄视频| 欧美日韩成人精品| 成人做爽爽免费视频| 中文字幕日韩有码| 美日韩精品免费观看视频| 欧美成人精品h版在线观看| 精品一区二区三区三区| 亚洲精品福利视频| 国产欧美精品一区二区三区介绍| 国产精品久久久久一区二区| 4388成人网| 国产精品丝袜久久久久久高清| 欧美日韩亚洲高清| 国产精品九九久久久久久久| 国产视频欧美视频| 国产69精品久久久久9999| 欧美激情欧美激情| 麻豆乱码国产一区二区三区| 国产精品极品尤物在线观看| 亚洲最大av网| 5566日本婷婷色中文字幕97| 隔壁老王国产在线精品| 久久伊人精品一区二区三区| 国产精品中文久久久久久久| www.日韩.com| y97精品国产97久久久久久| 亚洲人成在线免费观看| 欧美性猛交xxxx乱大交| 奇门遁甲1982国语版免费观看高清| 激情久久av一区av二区av三区| 日韩成人av一区| 日本不卡视频在线播放| 国产91在线高潮白浆在线观看| **欧美日韩vr在线| 亚洲色图偷窥自拍| 亚洲福利视频二区| 中文字幕久热精品在线视频| 久久久久成人精品| 亚洲欧美999| 欧美日韩一区二区免费在线观看| 欧美激情第一页xxx| 国产69精品99久久久久久宅男| 另类天堂视频在线观看| 亚洲欧美日韩精品| 日韩av电影免费观看高清| 亚洲自拍在线观看| 精品偷拍各种wc美女嘘嘘| 亚洲专区国产精品| 国产精品丝袜一区二区三区| 美日韩精品视频免费看| 国外成人性视频| 中文字幕亚洲综合| 国产欧美一区二区三区四区| 欧美理论电影网| 亚洲人精选亚洲人成在线| 日韩久久精品电影| 欧美高清视频免费观看| 热re91久久精品国99热蜜臀| 在线视频免费一区二区| 欧美日韩成人在线观看| 国产精品jizz在线观看麻豆| 亚洲一区二区免费在线| 亚洲伊人久久大香线蕉av| 亚洲自拍偷拍色图| 日韩av在线精品| 精品日韩视频在线观看| 91久久精品国产| 91精品国产91久久久久久久久| 日本精品免费一区二区三区| 国产z一区二区三区| 成人免费观看49www在线观看| 国产经典一区二区| 精品欧美一区二区三区| 欧美天堂在线观看| 57pao国产精品一区| 精品中文字幕乱| 精品国产欧美成人夜夜嗨| 精品网站999www| 国产噜噜噜噜久久久久久久久| 国产精品免费一区豆花| 国产亚洲福利一区| 欧美性猛交xxxx乱大交极品| 精品精品国产国产自在线| 91视频8mav| 欧美日韩中文字幕日韩欧美| 亚洲一区二区中文字幕| 欧美成人午夜视频| 最近2019中文字幕第三页视频| 欧美黄色免费网站| 高跟丝袜欧美一区| 在线观看国产精品91| 2019最新中文字幕| 国产精品久在线观看| 神马久久桃色视频| 久久青草精品视频免费观看| 日韩精品在线电影| 久久久久久久久久亚洲| 久久久人成影片一区二区三区| 日本欧美在线视频| 亚洲电影在线观看| 亚洲黄页网在线观看| 欧美一区在线直播| 最新的欧美黄色| www.欧美免费| 清纯唯美日韩制服另类| 亚洲午夜av电影| 国产成人jvid在线播放| 欧美寡妇偷汉性猛交| 亚洲欧美成人一区二区在线电影| 亚洲专区在线视频| 精品一区二区三区电影| 日韩高清有码在线| 68精品国产免费久久久久久婷婷| 欧美一级淫片videoshd| 一区二区三区久久精品| 亚洲护士老师的毛茸茸最新章节| 一区二区三区精品99久久| 精品久久久久久久大神国产| 欧美日韩中国免费专区在线看| 日韩欧美在线中文字幕| 亚洲第一av网站| 精品在线观看国产| 亚洲自拍偷拍一区| 欧美极品美女视频网站在线观看免费| 亚洲国产古装精品网站| 琪琪亚洲精品午夜在线| 欧美特黄级在线| 国产精品三级美女白浆呻吟| 亚洲成人网在线| 国产精品一区二区av影院萌芽| 成人免费在线视频网站| 亚洲free性xxxx护士hd| 久久亚洲精品中文字幕冲田杏梨| 亚洲国产精品电影在线观看| 热99精品只有里视频精品| 国产精品啪视频| 中文字幕一区日韩电影| 538国产精品一区二区免费视频| 精品久久久一区| 日韩欧美精品网址| 国产精品久久久久久网站| 亚洲自拍av在线| 日韩欧美精品免费在线| 亚洲一区第一页| 亚洲另类欧美自拍| 日韩女在线观看| 国产精品男人爽免费视频1| 欧美成aaa人片免费看| 欧美激情国产精品| 亚洲久久久久久久久久| 国产精品三级美女白浆呻吟| 成人中文字幕在线观看|