1. 程式人生 > >Spring入門第1天--IOC快速入門

Spring入門第1天--IOC快速入門

文件版本 開發工具 測試平臺 工程名字 日期 作者 備註
V1.0 2016.06.21 lutianfei none
  • 本文內容
    • Spring框架的概述
    • Spring的快速入門
    • Spring 工廠介面
    • 在MyEclipse 配置Spring的xml檔案提示
    • IoC容器裝配Bean(xml配置方式)
    • Ioc容器裝配Bean(註解方式)
    • 在web專案中整合Spring
    • Spring 整合 junit4 測試

Spring框架學習路線

  • Spring的Ioc
  • Spring的AOP , AspectJ
  • Spring的事務管理

Spring框架的概述

什麼是Spring

  • Spring是分層的JavaSE/EE full-stack(一站式) 輕量級開源框架

  • SUN提供的EE的三層結構:web層、業務層、資料訪問層(持久層,整合層)

    • Struts2是web層基於MVC設計模式框架.
    • Hibernate是持久的一個ORM的框架.
  • Spring框架有對三層的一站式解決方案:

    • web層:Spring MVC
    • 持久層:JDBC Template
    • 業務層:Spring的Bean管理
  • Spring的出現是為了取代EJB的臃腫、低效、脫離現實

Spring的核心

  • IOC:(Inverse of Control 反轉控制)

    • 控制反轉:將物件的建立權,交由Spring完成.
  • AOP : Aspect Oriented Programming 是 面向物件的功能延伸.不是替換面向物件,是用來解決OO中一些問題.

Spring的版本

  • Spring3.x和Spring4.x Spring4需要整合hibernate4.

Spring優點

  • 方便解耦,簡化開發
    • Spring就是一個大工廠,可以將所有物件建立和依賴關係維護,交給Spring管理
  • AOP程式設計的支援
    • Spring提供面向切面程式設計,可以方便的實現對程式進行許可權攔截、執行監控等功能
  • 宣告式事務的支援
    • 只需要通過配置就可以完成對事務的管理,而無需手動程式設計
  • 方便程式的測試
    • Spring對Junit4支援,可以通過註解方便的測試Spring程式
  • 方便整合各種優秀框架
    • Spring不排斥各種優秀的開源框架,其內部提供了對各種優秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的直接支援
  • 降低JavaEE API的使用難度
    • Spring 對JavaEE開發中非常難用的一些API(JDBC、JavaMail、遠端呼叫等),都提供了封裝,使這些API應用難度大大降低

Spring體系結構

  • Spring 框架是一個分層架構,它包含一系列的功能要素並被分為大約20個模組。這些模組分為Core Container、Data Access/Integration、Web、AOP(Aspect Oriented Programming)、Instrumentation和測試部分,如下圖所示:

Spring的快速入門

1. 下載Spring的開發包

  • Spring開發包 : spring-framework-3.2.0.RELEASE-dist.zip

    • docs : spring框架api和規範
    • libs : spring開發的jar包
    • schema : XML的約束文件.
  • Spring開發中的依賴包 : spring-framework-3.0.2.RELEASE-dependencies.zip

2. 建立web工程引入相應jar包

  • spring-beans-3.2.0.RELEASE.jar
  • spring-context-3.2.0.RELEASE.jar
  • spring-core-3.2.0.RELEASE.jar
  • spring-expression-3.2.0.RELEASE.jar

  • 開發的日誌記錄的包:

    • com.springsource.org.apache.commons.logging-1.1.1.jar : 用於整合其他的日誌的包(類似Hibernate中slf4j)
    • com.springsource.org.apache.log4j-1.2.15.jar

3. 建立Spring的配置檔案

  • 在src下建立一個applicationContext.xml
  • 引入XML的約束
    • 找到xsd-config.html.引入beans約束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- bean definitions here -->

</beans>

4. 在配置中配置類

<!-- 通過一個<bean>標籤設定類的資訊,通過id屬性為類起個標識. -->
<bean id="userService" class="cn.itcast.spring3.demo1.HelloServiceImpl"></bean>



5. 建立測試類

  • ApplicationContext 應用上下文,載入Spring 框架配置檔案
  • 載入classpath:
    • new ClassPathXmlApplicationContext(“applicationContext.xml”);
  • 載入磁碟路徑:
    • new FileSystemXmlApplicationContext(“applicationContext.xml”);
@Test

// Spring開發

public void demo2() {

    // 建立一個工廠類.

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(  "applicationContext.xml");

    HelloService helloService = (HelloService) applicationContext.getBean("userService");

    helloService.sayHello();

}

類建立的傳統方式

  • HelloTest類中使用 HelloService類物件

    • 傳統方式: HelloService helloService = new HelloService();
  • IoC Inverse of Control 反轉控制的概念,就是將原本在程式中手動建立HelloService物件的控制權,交由Spring框架管理,簡單說,就是建立HelloService物件控制權被反轉到了Spring框架

IOC和DI區別

  • IOC:控制反轉:將物件的建立權,由Spring管理.
  • DI:依賴注入:在Spring建立物件的過程中,把物件依賴的屬性注入到類中.

  • 面向物件中物件之間的關係;

    • 依賴:
    public class A{
    private B b;
    }
* 繼承:is a
* 聚合:
    * 聚集:
    * 組合:

BeanFactory與ApplicationContext區別

  • ApplicationContext類繼承了BeanFactory
  • BeanFactory在使用到這個類的getBean()方法的時候,才會載入這個類.
  • ApplicationContext類載入配置檔案的時候,建立所有的類
  • ApplicationContext對BeanFactory提供了擴充套件:

    • 國際化處理
    • 事件傳遞
    • Bean自動裝配
    • 各種不同應用層的Context實現
    • 早期開發使用BeanFactory.
  • Eg:

@Test

public void demo4(){

    // ClassPathResource  FileSystemResource

    BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("applicationContext.xml"))</u>;

    HelloService helloService = (HelloService) beanFactory.getBean("userService");

    helloService.sayHello();

}

MyEclipse配置XML提示

  • Myeclipse window-preferences- 搜尋xml catalog
  • 選中User Specified Entries – Add 操作
  • location 瀏覽選中 解壓spring 包中 schema\beans\spring-beans-3.2.xsd
  • 修改Key type 為 Schema location

Spring框架Bean例項化的方式

  • 三種方式例項化Bean
    • 構造方法例項化(預設無引數)
    • 靜態工廠例項化
    • 例項工廠例項化

無引數構造方法的例項化

<!-- 預設情況下使用的就是無引數的構造方法. -->
<bean id="bean1" class="cn.itcast.spring3.demo2.Bean1"></bean>

靜態工廠例項化 – 簡單工廠模式

<!-- 第二種使用靜態工廠例項化 -->

<bean id="bean2" class="cn.itcast.spring3.demo2.Bean2Factory" factory-method="getBean2"></bean>

例項工廠例項化 – 工廠方法模式

<!-- 第三種使用例項工廠例項化 -->

<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>

<bean id="bean3Factory" class="cn.itcast.spring3.demo2.Bean3Factory"/>

public class PersonServiceFactory {
    public  PersonService  createPersonService(){
        return new PersonServiceImpl();
       }
}
  • eg:
/**
 * Bean的例項化的測試
 * 
 * @author 姜濤
 * 
 */
public class SpringTest2 {
    @Test
    // 無引數的構造方法的例項化
    public void demo1() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        Bean1 bean1 = (Bean1) applicationContext.getBean("bean1");
        System.out.println(bean1);
    }

    @Test
    // 靜態工廠例項化
    public void demo2() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        Bean2 bean2 = (Bean2) applicationContext.getBean("bean2");
        System.out.println(bean2);
    }
    @Test
    // 例項工廠例項化
    public void demo3() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        Bean3 bean3 = (Bean3) applicationContext.getBean("bean3");
        System.out.println(bean3);
    }

Bean的其他配置

Bean的命名 id屬性和name屬性

  • 一般情況下,裝配一個Bean時,通過指定一個id屬性作為Bean的名稱
  • id 屬性在IoC容器中必須是唯一的
  • id 的命名要滿足XML對ID屬性命名規範
    • id遵守XML約束的id的約束.id約束保證這個屬性的值是唯一的,而且必須以字母開始,可以使用字母數字連字元下劃線句話冒號
  • 如果Bean的名稱中含有特殊字元,就需要使用name屬性
  • 例如:
    • <bean name="#person" class="cn.itcast.bean.Person"/>
  • 因為name屬性可以相同,所以後出現Bean會覆蓋之前出現的同名的Bean

類的作用範圍

  • scope屬性 :

    • singleton : 單例的(預設的值)
    • prototype : 多例的
    • request : web開發中建立了一個物件,將這個物件存入request範圍,request.setAttribute();
    • session : web開發中.建立了一個物件,將這個物件存入session範圍,session.setAttribute();
    • globalSession :一般用於Porlet應用環境.指的是分散式開發.不是porlet環境,globalSession等同於session;
  • 實際開發中主要使用 singleton,prototype

Bean的生命週期

  • 配置Bean的初始化和銷燬的方法:在xml檔案中加入:
    • init-method=”setup”
    • destroy-method=”teardown”

  • 執行銷燬的時候,必須手動關閉工廠,而且只對scope=singleton有效
    • 必須用子類執行 ClassPathXmlApplicationContext 中的close方法來實現。
Bean的生命週期的11個步驟
  • 1 . bean物件例項化 : instantiate bean
  • 2 . 屬性的注入: populate properties : 封裝屬性
  • 3 . 注入配置的類的名稱 : 如果Bean實現BeanNameAware 執行 setBeanName
  • 4 . 注入applicationContext : 如果Bean實現BeanFactoryAware 或者 k 設定工廠 setBeanFactory 或者上下文物件 setApplicationContext
  • 5 . 初始化之前執行操作如果存在類實現 BeanPostProcessor(後處理Bean),執行postProcessBeforeInitialization
    • 需要新增此標籤:<bean class="cn.itcast.spring3.demo4.MyBeanPostProcessor"></bean>
    • 6 . 屬性設定後執行操作 : 如果Bean實現InitializingBean 執行 afterPropertiesSet
  • 7 . 呼叫手動設定的初始化方法 : 呼叫<bean init-method="init"> 指定初始化方法 init
  • 8 . 初始化後執行操作如果存在類實現 BeanPostProcessor(處理Bean),執行 postProcessAfterInitialization
  • 9 . 執行業務處理
  • 10 . 呼叫銷燬的方法 : 如果Bean實現 DisposableBean 執行 destroy
  • 11 . 呼叫手動銷燬方法 : 呼叫<bean destroy-method="customerDestroy"> 指定銷燬方法 customerDestroy

  • 案例:在CustomerService類的add方法之前進行許可權校驗

  • xml配置

<bean id="customerService" class="cn.itcast.spring3.demo4.CustomerServiceImpl" init-method="setup" destroy-method="teardown">
        <property name="name" value="itcast"></property>
    </bean>

    <bean class="cn.itcast.spring3.demo4.MyBeanPostProcessor"></bean>
    //這裡不需要寫id,因為這是由Spring容器自動呼叫的。
  • CustomerService & CustomerServiceImpl
public interface CustomerService {
    public void add();
    public void find();
}



public class CustomerServiceImpl implements CustomerService, BeanNameAware,ApplicationContextAware,InitializingBean,DisposableBean   {
    private String name;

    public void setName(String name) {
        System.out.println("第二步:屬性的注入.");
        this.name = name;
    }

    public CustomerServiceImpl() {
        super();
        System.out.println("第一步:例項化類.");
    }

    public void add(){
        System.out.println("新增客戶...");
    }

    public void find(){
        System.out.println("查詢客戶...");
    }

    public void setBeanName(String name) {
        System.out.println("第三步:注入配置的類的名稱"+name);
    }

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        System.out.println("第四步:注入applicationContext"+applicationContext);
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("第六步:屬性設定後執行...");
    }

    public void setup(){
        System.out.println("第七步:呼叫手動設定的初始化方法...");
    }

    public void destroy() throws Exception {
        System.out.println("第十步:呼叫銷燬的方法...");
    }

    public void teardown(){
        System.out.println("第十一步:呼叫手動銷燬方法...");
    }
}
  • MyBeanPostProcessor
public class MyBeanPostProcessor implements BeanPostProcessor{
    /**
     * bean:例項物件
     * beanName:在配置檔案中配置的類的標識.
     */
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("第五步:初始化之前執行...");
        return bean;
    }

    public Object postProcessAfterInitialization(final Object bean, String beanName)
            throws BeansException {
        System.out.println("第八步:初始化後執行...");
        // 動態代理:
        if(beanName.equals("customerService")){
            Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces() , new InvocationHandler() {
                // 呼叫目標方法的時候,呼叫invoke方法.
                public Object invoke(Object proxy, Method method, Object[] args)
                        throws Throwable {
                    if("add".equals(method.getName())){
                        System.out.println("許可權校驗...");
                        Object result = method.invoke(bean, args);
                        //System.out.println(System.currentTimeMillis());
                        return result;
                    }
                    return method.invoke(bean, args);
                }
            });
            return proxy;
        }
        return bean;
    }

}
  • Spirng Test
public class SpringTest4 {

    @Test
    // Bean完整的生命週期
    public void demo1() {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        CustomerService customerService = (CustomerService) applicationContext.getBean("customerService");
        customerService.add();
        customerService.find();

        applicationContext.close();
    }
}


//結果如下:
第一步:例項化類
第二步:屬性的注入
第三步:注入配置的類的名稱 customerService
第四步:注入applicationContext org[email protected]61baa894: startup date [Wed Jun 22 11:49:14 CST 2016]; root of context hierarchy
第五步:初始化之前執行...
第六步:屬性設定後執行...
第七步:呼叫手動設定的初始化方法...
第八步:初始化後執行...
許可權校驗...
新增客戶...
查詢客戶...
11:49:14,863  INFO ClassPathXmlApplicationContext:1042 - Closing org[email protected]61baa894: startup date [Wed Jun 22 11:49:14 CST 2016]; root of context hierarchy
11:49:14,864  INFO DefaultListableBeanFactory:444 - Destroying singletons in org.s[email protected]64bfbc86: defining beans [customerService,test.spring3.demo4.MyBeanPostProcessor#0]; root of factory hierarchy
第十步:呼叫銷燬的方法...
第十一步:呼叫手動銷燬的方法...

IOC容器裝配Bean

Bean中屬性注入–基於XML方式

IoC容器裝配Bean 基於XML配置方式

  • Spring支援
    • 構造方法注入
    • setter方法注入

構造器注入

  • 使用構造方法注入,在Spring配置檔案中,通過 <constructor-arg>設定注入的屬性 (可以通過index或者type注入)




setter方法注入

  • 使用setter方法注入,在Spring配置檔案中,通過<property>設定注入的屬性

<bean id="car2" class="cn.itcast.spring3.demo5.Car2">
<!-- <property>標籤中name就是屬性名稱,value是普通屬性的值,ref:引用其他的物件 -->
<property name="name" value="保時捷"/>
<property name="price" value="5000000"/>
</bean>

setter方法注入物件屬性

  • <property>標籤中name就是屬性名稱,value是普通屬性的值,ref:引用其他的物件

名稱空間p:注入屬性

  • Spring2.5版本引入了名稱空間p

    • p:<屬性名>="xxx" 引入常量值
    • p:<屬性名>-ref="xxx" 引用其它Bean物件
  • 引入名稱空間:

    • xmlns:p="http://www.springframework.org/schema/p"
  • xml:

<bean id="car2" class="cn.itcast.spring3.demo5.Car2" p:name="寶馬" p:price="400000"/>

<bean id="person" class="cn.itcast.spring3.demo5.Person" p:name="童童" p:car2-ref="car2"/>

SpEL:屬性的注入

  • Spring3.0提供注入屬性方式:
  • 語法:<bean id="" value="#{表示式}">
    • #{'神回覆:哈哈'}使用字串
    • #{topicId3} 使用另一個bean
    • #{topicId4.content.toUpperCase()} 使用指定名屬性,並使用方法
    • #{T(java.lang.Math).PI} 使用靜態欄位或方法
<bean id="car2" class="cn.itcast.spring3.demo5.Car2">
    <property name="name" value="#{'大眾'}"></property>
    <property name="price" value="#{'120000'}"></property>
</bean>

<bean id="person" class="cn.itcast.spring3.demo5.Person">
    <!--<property name="name" value="#{personInfo.name}"/>-->
<property name="name" value="#{personInfo.showName()}"/>
    <property name="car2" value="#{car2}"/>
</bean>

<bean id="personInfo" class="cn.itcast.spring3.demo5.PersonInfo">
    <property name="name" value="張三"/>
</bean>
SpEL : 集合屬性的注入 – List(陣列)

SpEL : 集合型別屬性注入 – Set

SpEL : 集合型別屬性注入 – Map

SpEL :集合型別屬性注入 – Properties

  • 綜合案例
    <bean id="collectionBean" class="cn.itcast.spring3.demo6.CollectionBean">
        <!-- 注入List集合 -->
        <property name="list">
            <list>
                <value>童童</value>
                <value>小鳳</value>
            </list>
        </property>

        <!-- 注入set集合 -->
        <property name="set">
            <set>
                <value>杜巨集</value>
                <value>如花</value>
            </set>
        </property>

        <!-- 注入map集合 -->
        <property name="map">
            <map>
                <entry key="剛剛" value="111"/>
                <entry key="嬌嬌" value="333"/>
            </map>
        </property>

        <property name="properties">
            <props>
                <prop key="username">root</prop>
                <prop key="password">123</prop>
            </props>
        </property>
    </bean>

多配置檔案的載入

  • 第一種寫法:

    • ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml",”bean2.xml”);
  • 第二種方法:

    • <import resource="applicationContext2.xml"/>

Bean的屬性注入–基於註解方式

IoC容器裝配Bean , 基於註解配置方式

  • Spring2.5 引入註解去定義Bean

    • @Component 描述Spring框架中Bean
  • Xml:標頭檔案中加入context路徑:xmlns:context=http://www.springframework.org/schema/context

    • 最好直接從dsd-config.html中複製過來相應的程式碼段
<?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"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- bean definitions here -->

</beans>
  • 配置提示操作

    • 將紅框中地址複製到Key
  • 引入component-scan標籤:<context:component-scan base-package="cn.itcast.spring3"/>,告訴Spring要去掃描哪些包下的類。

  • Spring的框架中提供了與@Component註解等效的三個註解:
    @Repository 用於對DAO實現類進行標註
    @Service 用於對Service實現類進行標註
    @Controller 用於對Controller實現類進行標註
  • 三個註解是為了讓標註類本身的用途清晰,Spring在後續版本會對其增強

自動裝配 Bean

  • 使用@Autowired 進行自動注入
  • @Service 標註業務類
  • @Repository 標註DAO
  • @Autowired 預設按照型別進行注入
    • 如果存在兩個相同Bean型別,則按照名稱注入
    • @Autowired 注入時可以針對成員變數或者setter方法

  • 通過@Autowired的required屬性,設定一定要找到匹配的Bean,預設為true,為false時表示對異常不關心。
  • 使用@Qualifier指定注入Bean的名稱
    • 使用Qualifier 指定Bean名稱後,註解Bean必須指定相同名稱
普通屬性
  • @Value(value=”itcast”)
  • private String info;
物件屬性
  • 按型別注入
    • @Autowired:自動裝配預設使用型別注入.
  • 按名稱進行注入
    • @Autowired 中有一個屬性required,預設為true,為false時表示對異常不關心。
    • @Qualifier(“userDao”) 按名稱進行注入.

標準註解@Resource

  • Spring提供對JSR-250中定義@Resource標準註解的支援@Resource@Autowired註解功能相似

  • 下面兩個例子等價

@Autowired
@Qualifier("userDao")
private UserDao userDao;
@Resource(name="userDao")
private UserDao userDao;

Bean其他的屬性的配置

  • 配置Bean初始化方法和銷燬方法:
    • init-method 和 destroy-method.
    • @PostConstruct : 初始化
    • @PreDestroy : 銷燬

配置Bean的作用範圍

  • 使用註解配置的Bean和<bean>配置的一樣,預設作用範圍都是singleton
    • @Scope註解用於指定Bean的作用範圍

Spring3.0可以 使用Java類提供Bean定義資訊

  • Spring3.0以JavaConfig為核心,提供使用Java類定義Bean資訊的方法

    • @Configuration 指定POJO類為Spring提供Bean定義資訊,代表此類就是一個配置類。
    • @Bean 提供一個Bean定義資訊
  • 之前已經通過 component-scan標籤 對配置類進行了掃描,故這裡不需要再進行手動配置掃描了。

@Configuration
public class BeanConfig {

    @Bean(name="car")
    public Car showCar(){
        Car car = new Car();
        car.setName("長安");
        car.setPrice(40000d);
        return car;
    }

    @Bean(name="product")
    public Product initProduct(){
        Product product = new Product();
        product.setName("空調");
        product.setPrice(3000d);
        return product;
    }
}

實際開發中使用XML還是註解

  • XML:
    • bean管理
  • 註解:
    • 注入屬性的時候比較方便
  • 兩種方式結合;一般使用XML註冊Bean,使用註解進行屬性的注入

Spring整合web開發

  • 正常整合Servlet和Spring沒有問題的,但是每次執行Servlet的時候載入Spring配置以及載入Spring環境

  • 解決辦法:

    • 將載入的資訊內容放到ServletContext中.ServletContext物件是全域性的物件。伺服器啟動的時候建立的,在建立ServletContext的時候就載入Spring的環境。
    • ServletContextListener:用於監聽ServletContext物件的建立和銷燬的.
    • 以上解決方法可以通過匯入Spring web開發jar包來解決 : spring-web-3.2.0.RELEASE.jar

web.xml中的配置

  • 將Spring容器初始化,交由web容器負責
  • 配置核心監聽器 ContextLoaderListener
  • 配置全域性引數contextConfigLocation
    • 用於指定Spring的框架的配置檔案位置(因為:applicationContext.xml檔案與預設位置不一致)

<listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>
 <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:applicationContext.xml</param-value>
 </context-param>

獲得WebApplicationContext物件

  • 因為Spring容器已經交由web容器初始化和管理,獲得WebApplicationContext物件,需要依賴ServletContext物件 通常在Servlet中完成:
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
  • 另一種方式
WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  • eg:

  • web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
 <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
 </context-param>

  <servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>cn.itcast.servlet.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/userServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
  • UserServlet & UserService
public class UserServlet extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");*/
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

        UserService userService = (UserService) applicationContext
                .getBean("userService");
        userService.sayHello();
    }



public class UserService {

    public void sayHello(){
        System.out.println("Hello Spring web...");
    }
}

Spring整合JUnit測試

  • 1.程式中有Junit環境.
  • 2.匯入Spring test測試jar包
    • spring-test-3.2.0.RELEASE.jar
  • 3.測試程式碼:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
    public class SpringTest {
        @Autowired
        private UserService userService;

        @Test
        public void demo1(){
            userService.sayHello();
        }
}