[Spring框架]Spring開發實例: XML+注解.


前言: 本文為自己學習Spring記錄所用, 文章內容包括Spring的概述已經簡單開發, 主要涉及IOC相關知識, 希望能夠對新入門Spring的同學有幫助, 也希望大家一起討論相關的知識.

一. Spring概述


1.1,什么是Spring:
Spring是一個開源框架,Spring是於2003 年興起的一個輕量級的Java 開發框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中闡述的部分理念和原型衍生而來。它是為了解決企業應用開發的復雜性而創建的。框架的主要優勢之一就是其分層架構,分層架構允許使用者選擇使用哪一個組件,同時為 J2EE 應用程序開發提供集成的框架。Spring使用基本的JavaBean來完成以前只可能由EJB完成的事情。然而,Spring的用途不僅限於服務器端的開發。從簡單性、可測試性和松耦合的角度而言,任何Java應用都可以從Spring中受益。Spring的核心是控制反轉IoC)和面向切面(AOP)。簡單來說,Spring是一個分層的JavaSE/EE full-stack(一站式) 輕量級開源框架。

 

1.2, 為什么需要學習Spring

方便解耦,簡化開發

Spring就是一個大工廠,可以將所有對象創建和依賴關系維護,交給Spring管理

AOP編程的支持

Spring提供面向切面編程,可以方便的實現對程序進行權限攔截、運行監控等功能

聲明式事務的支持

只需要通過配置就可以完成對事務的管理,而無需手動編程

方便程序的測試

Spring對Junit4支持,可以通過注解方便的測試Spring程序

方便集成各種優秀框架

Spring不排斥各種優秀的開源框架,其內部提供了對各種優秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的直接支持

降低JavaEE API的使用難度

Spring 對JavaEE開發中非常難用的一些API(JDBC、JavaMail、遠程調用等),都提供了封裝,使這些API應用難度大大降低

二, Spring IOC 的快速入門
上一篇文章: http://www.cnblogs.com/wang-meng/p/5597490.html 已經對於IOC 的概念有了深入的解析, 在這里就不再贅述了, 直接說IOC 的快速開發.

2,1 快速開發入門
步驟一: 下載Spring的開發包:
為了方便大家開發, 我已經將spring-framework-3.2.4.RELEASE-dist.zip spring-framework-3.0.2.RELEASE-dependencies.zip上傳至我的網盤. 地址如下:
鏈接:http://pan.baidu.com/s/1slqvOzb 密碼:ikgn

步驟二: 了解Spring的目錄結構:

docs        :Spring的開發文檔
libs        :Spring的開發包.
schema      :約束文檔.


步驟三: 創建一個項目,引入jar包:



步驟四: 引入Spring的配置文件:

 1 在src下創建一個applicationContext.xml
 2 引入約束:
 3 <beans xmlns="http://www.springframework.org/schema/beans"
 4        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 6 
 7 </beans>
 8 
 9 編寫標簽:
10 <bean id="customerService" class="cn.augmentum.spring.demo2.CustomerServiceImpl"></bean>


驟五: 編寫測試類:

1     @Test
2     public void demo1(){
3         // 創建Spring的工廠類:
4         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
5         CustomerService customerService = (CustomerService) applicationContext
6                 .getBean("customerService");
7         customerService.sayHello();
8     }

 

2.2 IOC及DI
IOC: Inverse of Controller 控制反轉.將Bean 創建反轉給Spring容器.
DI: Dependency Injection 依賴注入.在Spring創建這個類的過程中,將這個類的依賴的屬性注入進去.

2.3 Spring的工廠類

ApplicationContext

    |----ClassPathXmlApplicationContext :解析類路徑下的XML的.

    |----FileSystemXmlApplicationContext :解析本地磁盤上的XML的.

 

 

BeanFactory和ApplicationContext都是Spring中的工廠:

    BeanFactory是Spring老版本的工廠類:

         * 第一次調用getBean方法的時候實例化類.

    ApplicationContext是Spring新版本的工廠類:

        * 在加載核心配置文件的時候,將所有的類實例化.


三, Spring的Bean管理(基於XML方式)

 3.1 Spring實例化Bean的方式

無參數構造方式(最常用)

 1     <!-- 無參數構造方法方式 -->
 2     <bean id="bean1" class="cn.augmentum.spring.demo3.Bean1"></bean>
 3 
 4     @Test
 5     /**
 6      * 無參數構造
 7      */
 8     public void demo1() {
 9         // 加載核心配置文件:
10         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
11                 "applicationContext.xml");
12         Bean1 bean1 = (Bean1) applicationContext.getBean("bean1");
13         System.out.println(bean1);
14     }

靜態工廠實例化方式:

 1 Bean2的靜態工廠:
 2 /**
 3  * Bean2的靜態工廠
 4  * @author jiangtao
 5  *
 6  */
 7 public class Bean2Factory {
 8 
 9     public static Bean2 getBean2(){
10         return new Bean2();
11     }
12 }
13 
14 配置文件:
15     <!-- 靜態工廠實例化方式 -->
16     <bean id="bean2" class="cn.augmentum.spring.demo3.Bean2Factory" factory-method="getBean2"/>
17 
18 代碼:
19     @Test
20     /**
21      * 靜態工廠實例化
22      */
23     public void demo2() {
24         // 加載核心配置文件:
25         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
26                 "applicationContext.xml");
27         Bean2 bean2 = (Bean2) applicationContext.getBean("bean2");
28         System.out.println(bean2);
29     }

實例工廠實例化方式:

 1 實例工廠:
 2 public class Bean3Factory {
 3 
 4     public Bean3 getBean3(){
 5         System.out.println("實例工廠執行了...");
 6         return new Bean3();
 7     }
 8 }
 9 
10 配置文件:
11     <!-- 實例工廠實例化方式 -->
12     <bean id="bean3Factory" class="cn.itcast.spring.demo3.Bean3Factory"/>
13     <bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"/>
14 
15 代碼:
16     @Test
17     /**
18      * 實例工廠實例化
19      */
20     public void demo3() {
21         // 加載核心配置文件:
22         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
23                 "applicationContext.xml");
24         Bean3 bean3 = (Bean3) applicationContext.getBean("bean3");
25         System.out.println(bean3);
26     }

 

3.2,  SpringBean的常用的配置:

<bean>標簽的idname屬性:

id和name有什么區別?

id :使用XML約束中ID約束.不可以出現特殊字符.

name:出現特殊字符.如果使用了name沒有id,那么name可以作為id使用.

Spring整合Struts1:  <bean name=”/login” class=””/>

<bean>上的生命周期的配置:

 1     @Test
 2     /**
 3      * Bean的生命周期的相關配置:
 4      *     * init-method
 5      *     * destory-method :只能針對單例對象有效.必須在工廠關閉之后才會銷毀對象.
 6      */
 7     public void demo1(){
 8         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
 9         EmployeeService employeeService = (EmployeeService) applicationContext
10                 .getBean("employeeService");
11         employeeService.save();
12         applicationContext.close();
13     }

<bean>上的作用范圍的配置:|

scope屬性:

* singleton :單例的.(默認)

* prototype :多例的.

* request :WEB項目中,創建一個對象,保存到request域中.

* session :WEB項目中,創建一個對象,保存到session域中.

* globalsession :WEB項目中,特殊環境.分布式開發環境.如果沒有分布式環境,相當於session.

3.3 Bean的生命周期:

Spring實例化Bean的過程中總共完成11個步驟:
1.instantiate bean對象實例化

2.populate properties 封裝屬性

3.如果Bean實現BeanNameAware 執行 setBeanName

4.如果Bean實現BeanFactoryAware 或者 ApplicationContextAware 設置工廠 setBeanFactory 或者上下文對象 setApplicationContext

5.如果存在類實現 BeanPostProcessor(后處理Bean) ,執行postProcessBeforeInitialization

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

第三步和第四步:主要讓生成Bean了解Spring容器.

第五步和第八步:允許客戶在Bean的生成過程中對Bean的實例進行增強.

* BeanPostProcessor:工廠勾子.允許客戶在生成類的過程中對類進行增強.

四, Spring的屬性注入:

4.1 構造方法的屬性注入:

1 <!-- 構造方法的注入 -->
2 
3 <bean id="car" class="cn.augmentum.spring.demo6.Car">
5   <constructor-arg name="name" value="寶馬"/>
7   <constructor-arg name="price" value="1000000"/>
9 </bean>

4.2 Set方法的屬性注入:

1 <!-- set方法的屬性注入 -->
2 
3 <bean id="car2" class="cn.augmentum.spring.demo6.Car2">
5   <property name="name" value="奇瑞QQ"/>
7   <property name="price" value="30000"/>
9 </bean>

4.3 Spring2.5支持p名稱空間的注入:

P名稱空間的語法:

語法:

* 普通屬性:   p:name=””

* 對象類型屬性:  p:name-ref=””

 

 



P名稱空間的使用:

 1 引入p名稱空間:
 2 
 3 <beans xmlns="http://www.springframework.org/schema/beans"
 4 
 5    xmlns:p="http://www.springframework.org/schema/p"
 6 
 7        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 8 
 9        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
10 
11  
12 
13 <!-- p名稱空間的注入 -->
14 
15 <bean id="car2" class="cn.augmentum.spring.demo6.Car2" p:name="長安奔奔" p:price="25000"/>
16 
17 <bean id="employee" class="cn.augmentum.spring.demo6.Employee" p:name="馬鳳" p:car2-ref="car2"/>

4.4 Spring3.0SpEL的屬性注入(SpEL:Spring Expression Language)

SpEL的語法:

語法:#{SpEL}

 

SpEL的用法:

1 <bean id="carInfo" class="cn.augmentum.spring.demo6.CarInfo">
2 
3 </bean>
 1 <!-- SpEL的方式的屬性注入 -->
 2 
 3 <bean id="car2" class="cn.augmentum.spring.demo6.Car2">
 5   <property name="name" value="#{carInfo.carName}"/>
 7   <property name="price" value="#{carInfo.calculatorPrice()}"/>
 9 </bean>
10 
11  
12 
13 <bean id="employee" class="cn.augmentum.spring.demo6.Employee">
15   <property name="name" value="濤哥"/>
17   <property name="car2" value="#{car2}"/>
19 </bean>

 

4.5 Spring中的數組或集合的屬性的注入: 1 <!--數組屬性的注入:-->

 2 
 3 <property name="arrs">
 5   <list>
 7     <value>老馬</value>
 9     <value>馬鳳</value>
11     <value>馬如花</value>
13   </list>
15 </property>
16 
17 <!--List集合的屬性的注入:-->
19 <property name="list">
21   <list>
23     <value>馬芙蓉</value>
25     <value>馬大帥</value>
27     <value>馬大彪</value>
29   </list>
31 </property>
32 
33 <!--Set集合的屬性的注入:-->
35 <property name="set">
37   <set>
39     <value>馬雲</value>
41     <value>馬化騰</value>
43     <value>馬大哈</value>
45   </set>
46 
47 </property>
48 
49 <!--Map集合的屬性的注入:-->
51 <property name="map">
53   <map>
55     <entry key="aaa" value="劉能"/>
57     <entry key="bbb" value="趙四"/>
59     <entry key="ccc" value="王五"/>
61   </map>
63 </property>
64 
65 <!--Properties的屬性的注入:-->
67 <property name="properties">
69   <props>
71     <prop key="username">root</prop>
73     <prop key="password">123</prop>
75   </props>
77 </property>

4.6 Spring中的分配置文件進行開發:

加載配置文件的時候加載多個配置文件:

 1 @Test
 2 
 3 /**
 4 
 5  * 在加載配置文件的時候,加載多個配置文件
 6 
 7  */
 8 
 9 public void demo2() {
10 
11     ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml", "applicationContext2.xml");
12 
13     CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean");
14 
15     System.out.println(collectionBean);
16 
17 }

總配置文件中引入其他配置文件:

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

 1 @Test
 2 
 3 /**
 4 
 5  * 在一個配置文件中引入其他的配置文件
 6 
 7  */
 8 
 9 public void demo3() {
10 
11   ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
14 
15   CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean");
18 
19   System.out.println(collectionBean);
20 
21 }

 

五, SpringBean管理(基於注解方式)

5.1 Spring的注解的快速入門:

步驟一:創建項目,引入jar:

步驟二:引入spring的配置文件:

如果使用Spring的注解的開發,需要引入context約束!!!

 1 <beans xmlns="http://www.springframework.org/schema/beans"
 2 
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4 
 5        xmlns:context="http://www.springframework.org/schema/context"
 6 
 7        xsi:schemaLocation="
 8 
 9 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
10 
11 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

步驟三:創建包和類:

* cn.augmentum.spring.demo1

* UserService

* UserServiceImpl

步驟四:在類上配置一個注解:

1 @Component(value="userService")
2 
3 相當於:
4 
5 <bean id=”userService” class=”…UserServiceImpl”/>

步驟五:Spring中開啟注解掃描:

1 <context:component-scan base-package="cn.augmentum.spring.demo1"/>

5.2 SpringIOC的注解詳解:

@Component:組件.

Spring提供了@Component的注解的一些衍生注解:

* @Controller :

* @Service :

* @Repository :

@Value:注入普通類型的屬性.

@Value(value=”張三”)

private String name;

@Autowired

默認按類型完成屬性的注入:

* 但是我們習慣采用按名稱注入.

* 強制使用按名稱的方式完成屬性的注入:

* @Qulifer(value=”名稱”)

@Resource:

@Resource注解相當於:

* @Autowired@Qulifer一起使用完成按名稱的屬性注入.

5.3 SpringIOC的其他的注解:

@PostConstruct:

相當於init-method

@PreDestory:

相當於destory-method

@Scope:

相當於scope屬性:

* singleton

* prototype

* request

* session

* globalSession

5.4 Spring3.0基於JavaConfig為核心的注解

JavaConfig為核心:使用Java類作為配置文件.

* 類的構造特別麻煩!!!

 

 1 @Configuration
 2 public class BeanConfig {
 3 
 4     @Bean(name="car")
 5     public Car showCar(){
 6 
 7         Car car = new Car();
 8 
 9         car.setName("馬自達");
10 
11         car.setPrice(150000d);
12 
13         return car;
14     }
15 
16  
17 
18     @Bean(name="product")
19     public Product showProduct(){
20 
21         Product product = new Product();
22 
23         product.setName("空調");
24 
25         product.setPrice(1200d);
26 
27         return product;
28 
29     }
30 
31 }

 

5.5 XML和注解的比較:

XML:結構清晰.(Bean管理由Spring控制.)

注解:開發便捷.(屬性注入:不需要提供set方法.)

 

企業中通常還有一種開發方式:XML和注解的整合開發.

* XML用於管理Bean.

* 注解用於屬性注入.

需要在配置文件中開啟注解配置:

<context:annotation-config/>

Bean交給Spring進行管理.屬性注入由注解完成.

到了這里就說完了Spring IOC的相關知識, 准備下一篇文章總結下AOP的相關知識. 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM