spring學習筆記1

         spring簡介 

       spring是一個優秀的框架,它的核心是控制反轉和依賴注入。所謂控制反轉是指,應用本身不負責依賴對象的創建及維護,依賴對象的創建和維護是由外部容器負責的,控制權的轉移就是控制反轉;依賴注入是指,由外部容器動態的將依賴對象注入到組件中。

      優點:①降低組件之間的耦合度,實現軟件各層之間的解耦。

                  ②使用容器爲其提供衆多服務,事務管理服務(開啓和關閉事務)、JMS服務、持久化服務、spring core 核心服務等。

                  ③容器提供單例模式的支持,開發人員不在需要自己編寫實現代碼。

                  ④容器提供AOP技術,利用他容易實現權限攔截等功能。

                  ⑤提供輔助類,JDBCtemplate, HibernateTemplate,能加快應用的開發。

                  ⑥對於主流框架提供了集成支持。

        界定一個框架是輕或者重的框架,是看使用它時,它開啓的服務的多少來決定的。

         spring開發環境的搭建

      使用spring所需要的包:
      

            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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
          <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
</beans>
 配置好bean之後,該bean就被spring容器管理。            

 實例化容器

   
    調用
    PersonService  p= ( PersonService) ctx.getBean("personService");
    p.save();  
    

spring實例化bean的三種方式:


一、使用構造器實例化;

  1. <!--applicationContext.xml配置:-->  
  2.   
  3. <bean id="personService" class="cn.mytest.service.impl.PersonServiceBean"></bean>

二、使用靜態工廠方法實例化;

  1. public void instanceSpring(){  
  2.                 //加載spring配置文件  
  3.         ApplicationContext ac = new ClassPathXmlApplicationContext(  
  4.                 new String[]{  
  5.                         "/conf/applicationContext.xml"  
  6.                 });  
  7.         //調用getBean方法取得被實例化的對象。  
  8.         PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService");  
  9.           
  10.         psb.save();  
  11. }  

三、使用實例化工廠方法實例化。

  1. package cn.mytest.service.impl;  
  2.   
  3. /** 
  4. *創建工廠類 
  5. * 
  6. */  
  7. public class PersonServiceFactory {  
  8.     //創建靜態方法  
  9.     public static PersonServiceBean createPersonServiceBean(){  
  10.          //返回實例化的類的對象  
  11.         return new PersonServiceBean();  
  12.     }  
  13. }  
xml代碼

  1. <!--applicationContext.xml配置:-->  
  2.   
  3. <bean id="personService1" class="cn.mytest.service.impl.PersonServiceFactory" factory-method="createPersonServiceBean"></bean> 
java代碼

  1. public void instanceSpring(){  
  2.                 //加載spring配置文件  
  3.         ApplicationContext ac = new ClassPathXmlApplicationContext(  
  4.                 new String[]{  
  5.                         "/conf/applicationContext.xml"  
  6.                 });  
  7.         //調用getBean方法取得被實例化的對象。  
  8.         PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService1");  
  9.           
  10.         psb.save();  
  11. }  








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