Spring入門一

  • Spring框架的概述
  • Spring的快速入門
  • Spring 工廠接口
  • 在MyEclipse 配置Spring的xml文件提示
  • IoC容器裝配Bean(xml配置方式)
  • Ioc容器裝配Bean(註解方式)
  • 在web項目中集成Spring
  • Spring 整合 junit4 測試

1.1 Spring框架學習路線:

Spring的Ioc
Spring的AOP , AspectJ
Spring的事務管理 , 三大框架的整合.

1.2 Spring框架的概述:

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

  • 分層:
  • SUN提供的EE的三層結構:web層、業務層、數據訪問層(持久層,集成層)
  • Struts2是web層基於MVC設計模式框架.
  • Hibernate是持久的一個ORM的框架.
  • 一站式:
  • Spring框架有對三層的每層解決方案:
  • web層:Spring MVC.
  • 持久層:JDBC Template
  • 業務層:Spring的Bean管理.

1.2.2 Spring的核心:
IOC:(Inverse of Control 反轉控制)
* 控制反轉:將對象的創建權,交由Spring完成.
AOP:Aspect Oriented Programming 是 面向對象的功能延伸.不是替換面向對象,是用來解決OO中一些問題.
IOC:控制反轉.

1.2.3 Spring的版本:
Spring3.x和Spring4.x Spring4需要整合hibernate4.

1.2.4 EJB:企業級JavaBean
EJB:SUN公司提出EE解決方案.

2002 : Expert One-to-One J2EE Design and Development
2004 : Expert One-to-One J2EE Development without EJB (EE開發真正需要使用的內容.)
1.2.5 Spring優點:
方便解耦,簡化開發
* Spring就是一個大工廠,可以將所有對象創建和依賴關係維護,交給Spring管理
AOP編程的支持
* Spring提供面向切面編程,可以方便的實現對程序進行權限攔截、運行監控等功能
聲明式事務的支持
* 只需要通過配置就可以完成對事務的管理,而無需手動編程
方便程序的測試
* Spring對Junit4支持,可以通過註解方便的測試Spring程序
方便集成各種優秀框架
* Spring不排斥各種優秀的開源框架,其內部提供了對各種優秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的直接支持
降低JavaEE API的使用難度
* Spring 對JavaEE開發中非常難用的一些API(JDBC、JavaMail、遠程調用等),都提供了封裝,使這些API應用難度大大降低
*
1.3 Spring的入門的程序:
1.3.1 下載Spring的開發包:

spring-framework-3.2.0.RELEASE-dist.zip —Spring開發包
* docs :spring框架api和規範
* libs :spring開發的jar包
* schema :XML的約束文檔.

1.3.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

1.3.3 創建Spring的配置文件:
在src下創建一個applicationContext.xml
引入XML的約束:
* 找到xsd-config.html.引入beans約束:

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

1.3.4 在配置中配置類:

1.3.5 創建測試類:

@Test
    // Spring開發
    public void demo2() {
        // 創建一個工廠類.
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        HelloService helloService = (HelloService) applicationContext.getBean("userService");
        helloService.sayHello();
    }

1.3.6 IOC和DI(*)區別?
IOC:控制反轉:將對象的創建權,由Spring管理.
DI:依賴注入:在Spring創建對象的過程中,把對象依賴的屬性注入到類中.
* 面向對象中對象之間的關係;
* 依賴:
public class A{
private B b;
}
* 繼承:is a
* 聚合:
* 聚集:
* 組合:

1.3.7 Spring框架加載配置文件:
ApplicationContext 應用上下文,加載Spring 框架配置文件
加載classpath:
new ClassPathXmlApplicationContext(“applicationContext.xml”); :加載classpath下面配置文件.
加載磁盤路徑:
new FileSystemXmlApplicationContext(“applicationContext.xml”); :加載磁盤下配置文件.

1.3.8 BeanFactory與ApplicationContext區別?
ApplicationContext類繼承了BeanFactory.
BeanFactory在使用到這個類的時候,getBean()方法的時候纔會加載這個類.
ApplicationContext類加載配置文件的時候,創建所有的類.
ApplicationContext對BeanFactory提供了擴展:
* 國際化處理
* 事件傳遞
* Bean自動裝配
* 各種不同應用層的Context實現

1.3.9 MyEclipse配置XML提示:
Window—>xml catalog—>add 找到schema的位置 ,將複製的路徑 copy指定位置,選擇schema location.

1.4 IOC裝配Bean:
1.4.1 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"/>

1.4.2 Bean的其他配置:
id和name的區別:
id遵守XML約束的id的約束.id約束保證這個屬性的值是唯一的,而且必須以字母開始,可以使用字母、數字、連字符、下劃線、句話、冒號
name沒有這些要求
* 如果bean標籤上沒有配置id,那麼name可以作爲id.
* 開發中Spring和Struts1整合的時候, /login.

現在的開發中都使用id屬性即可.
類的作用範圍:
scope屬性 :
* singleton :單例的.(默認的值.)
* prototype :多例的.
* request :web開發中.創建了一個對象,將這個對象存入request範圍,request.setAttribute();
* session :web開發中.創建了一個對象,將這個對象存入session範圍,session.setAttribute();
* globalSession :一般用於Porlet應用環境.指的是分佈式開發.不是porlet環境,globalSession等同於session;

實際開發中主要使用singleton,prototype

Bean的生命週期:
配置Bean的初始化和銷燬的方法:
配置初始化和銷燬的方法:
* init-method=”setup”
* destroy-method=”teardown”
執行銷燬的時候,必須手動關閉工廠,而且只對scope=”singleton”有效.

  • 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.調用 指定初始化方法 init
    8.如果存在類實現 BeanPostProcessor(處理Bean) ,執行postProcessAfterInitialization
    9.執行業務處理
    10.如果Bean實現 DisposableBean 執行 destroy
    11.調用 指定銷燬方法 customerDestroy

在CustomerService類的add方法之前進行權限校驗?

1.4.3 Bean中屬性注入:
Spring支持構造方法注入和setter方法注入:
構造器注入:

<bean id="car" class="cn.itcast.spring3.demo5.Car">
        <!-- <constructor-arg name="name" value="寶馬"/>
        <constructor-arg name="price" value="1000000"/> -->
        <constructor-arg index="0" type="java.lang.String" value="奔馳"/>
        <constructor-arg index="1" type="java.lang.Double" value="2000000"/>
    </bean>

setter方法注入:

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

setter方法注入對象屬性:

名稱空間p:注入屬性:
Spring2.5版本引入了名稱空間p.
p:<屬性名>=”xxx” 引入常量值
p:<屬性名>-ref=”xxx” 引用其它Bean對象

引入名稱空間:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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 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="#{表達式}">

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

1.4.4 集合屬性的注入:

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

1.4.5 加載配置文件:
一種寫法:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“bean1.xml”,”bean2.xml”);
二種方法:

1.5 IOC裝配Bean(註解方式)
1.5.1 Spring的註解裝配Bean
Spring2.5 引入使用註解去定義Bean
@Component 描述Spring框架中Bean

Spring的框架中提供了與@Component註解等效的三個註解:
@Repository 用於對DAO實現類進行標註
@Service 用於對Service實現類進行標註
@Controller 用於對Controller實現類進行標註
* 三個註解爲了後續版本進行增強的.

1.5.2 Bean的屬性注入:
普通屬性;
@Value(value=”itcast”)
private String info;

對象屬性:
@Autowired:自動裝配默認使用類型注入.
@Autowired
@Qualifier(“userDao”) — 按名稱進行注入.

@Autowired
@Qualifier(“userDao”)
private UserDao userDao;
等價於
@Resource(name=”userDao”)
private UserDao userDao;
1.5.3 Bean其他的屬性的配置:
配置Bean初始化方法和銷燬方法:
* init-method 和 destroy-method.
@PostConstruct 初始化
@PreDestroy 銷燬

配置Bean的作用範圍:
@Scope
1.5.4 Spring3.0提供使用Java類定義Bean信息的方法

@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;
    }
}

1.5.5 實際開發中使用XML還是註解?
XML:
* bean管理
註解;
* 注入屬性的時候比較方便.

兩種方式結合;一般使用XML註冊Bean,使用註解進行屬性的注入.


s
@Autowired
@Qualifier(“orderDao”)
private OrderDao orderDao;

1.6 Spring整合web開發:
正常整合Servlet和Spring沒有問題的
但是每次執行Servlet的時候加載Spring配置,加載Spring環境.
* 解決辦法:在Servlet的init方法中加載Spring配置文件?
* 當前這個Servlet可以使用,但是其他的Servlet的用不了了!!!
* 將加載的信息內容放到ServletContext中.ServletContext對象時全局的對象.服務器啓動的時候創建的.在創建ServletContext的時候就加載Spring的環境.
* ServletContextListener:用於監聽ServletContext對象的創建和銷燬的.

導入;spring-web-3.2.0.RELEASE.jar
在web.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 applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

1.7 Spring集成JUnit測試:
1.程序中有Junit環境.
2.導入一個jar包.spring與junit整合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();
    }
}

今天的內容總結:
Hibernate:知識點比較多.
Spring:AOP. 面向切面的思想.
Spring框架 IOC. AOP . 數據訪問 . 集成 . Web
* IOC:控制反轉.將對象的創建權交給Spring.
* DI:依賴注入.DI需要有IOC環境的,DI在創建對象的時候,將對象的依賴的屬性,一併注入到類中.
IOC裝配Bean:(XML)
*
* 配置Bean其他的屬性:
* init-method destroy-method scope

  • DI注入屬性:
  • 普通屬性:
  • 對象屬性:
  • 集合屬性的注入:
    IOC裝配Bean:(註解)
    @Component 描述Spring框架中Bean
    @Repository 用於對DAO實現類進行標註
    @Service 用於對Service實現類進行標註
    @Controller 用於對Controller實現類進行標註

DI屬性注入
* 普通屬性:
* @Value
* 對象屬性:
* AutoWired
* Resource

Bean的生命週期:
* 後處理Bean.BeanPostProcessor類.

Spring整合Web項目:
Spring整合Junit測試:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章