SSM03_Spring學習02_基於XML和註解的AOP配置

Spring學習筆記

AOP的相關概念

AOP概述

什麼是AOP

  • AOP:全稱是 Aspect Oriented Programming 即:面向切面編程
  • 簡單的說它就是把我們程序重複的代碼抽取出來,在需要執行的時候,使用動態代理的技術,在不修改源碼的基礎上對我們的已有方法進行增強

AOP的作用及優勢

  • 作用
    • 在程序運行期間,不修改源碼對已有方法進行增強。
  • 優勢
    • 減少重複代碼
    • 提高開發效率
    • 維護方便

AOP的實現方式

  • 使用動態代理技術

AOP的具體應用

動態代理回顧

  • 動態代理的特點

    • 字節碼隨用隨創建,隨用隨加載
    • 它與靜態代理的區別也在於此。因爲靜態代理是字節碼一上來就創建好,並完成加載。
    • 裝飾者模式就是靜態代理的一種體現
  • 動態代理常用的兩種方式

    • 基於接口的動態代理
      • 提供者:JDK 官方的 Proxy 類。
      • 要求:被代理類最少實現一個接口。
    • 基於子類的動態代理
      • 提供者:第三方的 CGLib,如果報 asmxxxx 異常,需要導入 asm.jar。
      • 要求:被代理類不能用 final 修飾的類(最終類)。
  • 使用JDK官方的Proxy類創建代理對象

    • 一個演員的例子:

      • 在很久以前,演員和劇組都是直接見面聯繫的。沒有中間人環節。

      • 而隨着時間的推移,產生了一個新興職業:經紀人(中間人),這個時候劇組再想找演員就需要通過經紀 人來找了。下面我們就用代碼演示出來。

        /** 
         * 一個經紀公司的要求:  
         *   能做基本的表演和危險的表演 
         */ 
         public interface IActor {
         	/** 
          	* 基本演出   
          	* @param money   
          	*/  
          	public void basicAct(float money);  
          	/** 
          	* 危險演出   
          	* @param money   
          	*/  
          	public void dangerAct(float money); 
          } 
         
         /** 
         * 一個演員  
         */ 
        //實現了接口,就表示具有接口中的方法實現。即:符合經紀公司的要求 
        public class Actor implements IActor{    
        	public void basicAct(float money){ 
          		System.out.println("拿到錢,開始基本的表演:"+money);  
          	}    
          	public void dangerAct(float money){   
          		System.out.println("拿到錢,開始危險的表演:"+money);  
          	} 
         } 
        
        public class Client {
        	public static void main(String[] args) {
            
          		//一個劇組找演員:   
          		final Actor actor = new Actor();//直接      
          		/** 
           		* 代理:    
           		*  間接。    
                * 獲取代理對象:    
                *  要求:    
                *   被代理類最少實現一個接口    
                * 創建的方式    
                *   Proxy.newProxyInstance(三個參數)    
                * 參數含義:    
                *  ClassLoader:和被代理對象使用相同的類加載器。    
                *  Interfaces:和被代理對象具有相同的行爲。實現相同的接口。    
                *  InvocationHandler:如何代理。    
                *    策略模式:使用場景是: 
           		*       數據有了,目的明確。    
           		*       如何達成目標,就是策略。    
           		*         
           		*/   
           		IActor proxyActor = (IActor) Proxy.newProxyInstance(
                actor.getClass().getClassLoader(),
                actor.getClass().getInterfaces(),
                new InvocationHandler() {     
                /** 
           		* 執行被代理對象的任何方法,都會經過該方法。      
           		* 此方法有攔截的功能。      
           		*  
             	* 參數:      
             	*  proxy:代理對象的引用。不一定每次都用得到      
             	*  method:當前執行的方法對象      
             	*  args:執行方法所需的參數      
             	* 返回值:      
             	*  當前執行方法的返回值      
             	*/     
             	@Override     
             	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                	String name = method.getName();
                    Float money = (Float) args[0];      
                    Object rtValue = null;
                    //每個經紀公司對不同演出收費不一樣,此處開始判斷
                    if("basicAct".equals(name)){       
                        //基本演出,沒有 2000 不演       
                        if(money > 2000){        
                            //看上去劇組是給了 8000,實際到演員手裏只有 4000        				//這就是我們沒有修改原來 basicAct 方法源碼,對方法進行了增強        
                            rtValue = method.invoke(actor, money/2);       
                        } 
             		}      
                    if("dangerAct".equals(name)){ 
                    //危險演出,沒有 5000 不演       
                        if(money > 5000){ 
                            //看上去劇組是給了 50000,實際到演員手裏只有 25000        			//這就是我們沒有修改原來 dangerAct 方法源碼,對方法進行了增強        
                            rtValue = method.invoke(actor, money/2);       
                        }      
                    }      
                  return rtValue;     
               } 
          }); 
          //沒有經紀公司的時候,直接找演員。 
            //  actor.basicAct(1000f); 
            //  actor.dangerAct(5000f);    
          	//劇組無法直接聯繫演員,而是由經紀公司找的演員   
                proxyActor.basicAct(8000f);   
                proxyActor.dangerAct(50000f);  } 
        } 
        

Spring中的AOP

Spring中AOP的細節

AOP相關術語

  • Joinpoint(連接點):
    • 所謂連接點是指那些被攔截到的點。在 spring 中,這些點指的是方法,因爲 spring 只支持方法類型的 連接點。
  • Pointcut(切入點):
    • 所謂切入點是指我們要對哪些 Joinpoint 進行攔截的定義。
  • Advice(通知/增強):
    • 所謂通知是指攔截到 Joinpoint 之後所要做的事情就是通知。
    • 通知的類型:前置通知,後置通知,異常通知,最終通知,環繞通知。
  • Introduction(引介):
    • 引介是一種特殊的通知在不修改類代碼的前提下, Introduction 可以在運行期爲類動態地添加一些方 法或 Field。
  • Target(目標對象):
    • 代理的目標對象。
  • Weaving(織入):
    • 是指把增強應用到目標對象來創建新的代理對象的過程。 spring 採用動態代理織入,而 AspectJ 採用編譯期織入和類裝載期織入。
  • Proxy(代理):
    • 一個類被 AOP 織入增強後,就產生一個結果代理類。
  • Aspect(切面):
    • 是切入點和通知(引介)的結合。

學習spring中的AOP要明確的事

  • 開發階段(我們做的)
    • 編寫核心業務代碼(開發主線):大部分程序員來做,要求熟悉業務需求。
    • 把公用代碼抽取出來,製作成通知。(開發階段最後再做):AOP 編程人員來做。
    • 在配置文件中,聲明切入點與通知間的關係,即切面。:AOP 編程人員來做。
  • 運行階段(Spring框架完成的)
    • Spring 框架監控切入點方法的執行。一旦監控到切入點方法被運行,使用代理機制,動態創建目標對 象的代理對象,根據通知類別,在代理對象的對應位置,將通知對應的功能織入,完成完整的代碼邏輯運行。

關於代理的選擇

  • 在 spring 中,框架會根據目標類是否實現了接口來決定採用哪種動態代理的方式。

基於XML的AOP配置

環境搭建

  • 第一步:準備必要的代碼 (實體類,業務層和持久層代碼。)

  • 第二步:拷貝必備的 jar 包到工程的 lib 目錄

  • 第三步:創建 spring 的配置文件並導入約束

    <!--此處要導入 aop 的約束  -->
    <?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:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans               http://www.springframework.org/schema/beans/spring-beans.xsd
              http://www.springframework.org/schema/aop
              http://www.springframework.org/schema/aop/spring-aop.xsd"> 
    </beans> 
    
  • 第四步:配置 spring 的 ioc

    <!-- 配置 service --> <bean id="accountService" class="com.service.impl.AccountServiceImpl"> 
     	<property name="accountDao" ref="accountDao"></property> 
    </bean> 
     
    <!-- 配置 dao --> <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
     	<property name="dbAssit" ref="dbAssit"></property> 
    </bean>   
    <!-- 配置數據庫操作對象 --> <bean id="dbAssit" class="com.itheima.dbassit.DBAssit"> 
     	<property name="dataSource" ref="dataSource"></property> 
     <!-- 指定 connection 和線程綁定 -->  
      	<property name="useCurrentConnection" value="true"></property> 
    </bean>   
    <!-- 配置數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///spring"></property>
     	<property name="user" value="root"></property>  
        <property name="password" value="root"></property> 
    </bean>
    
  • 第五步:抽取公共代碼製作成通知

    public class TransactionManager {
    
     //定義一個 DBAssit
     private DBAssit dbAssit ; 
     
     public void setDbAssit(DBAssit dbAssit) {
     	this.dbAssit = dbAssit;  
     	} 
     
     //開啓事務
     public void beginTransaction() {
     	try {
        	dbAssit.getCurrentConnection().setAutoCommit(false);   
        	} catch (SQLException e) {
            	e.printStackTrace(); 
      		}  
      	}
      //提交事務
      public void commit() {
      	try {    
      		dbAssit.getCurrentConnection().commit();   
      		} catch (SQLException e) {
            	e.printStackTrace();   
            }  
        } 
      //回滾事務
      public void rollback() {
      	try {    
      		dbAssit.getCurrentConnection().rollback();   
      		} catch (SQLException e) {    
      			e.printStackTrace();   
      		}  
      	}   
     //釋放資源
     public void release() {
     	try {    
     		dbAssit.releaseConnection();   
     		} catch (Exception e) {
            	e.printStackTrace();   
            }  
         } 
     } 
    

配置步驟

  • 第一步:把通知類用 bean 標籤配置起來

    <!-- 配置通知 --> 
     <bean id="txManager" class="com.itheima.utils.TransactionManager">  
     	<property name="dbAssit" ref="dbAssit"></property> 
     </bean>  
    
  • 第二步:使用 aop:config 聲明 aop 配置

    • aop:config:
      作用:用於聲明開始 aop 的配置
     <aop:config>
      <!-- 配置的代碼都寫在此處 -->  
     </aop:config> 
    
  • 第三步:使用 aop:aspect 配置切面

    • aop:aspect:
      作用:
      用於配置切面。
      屬性:
      id:給切面提供一個唯一標識。
      ref:引用配置好的通知類 bean 的 id。
     <aop:aspect id="txAdvice" ref="txManager"> 
      <!--配置通知的類型要寫在此處--> 
     </aop:aspect> 
    
  • 第四步:使用 aop:pointcut 配置切入點表達式

    • aop:pointcut:
      作用:
      用於配置切入點表達式。就是指定對哪些類的哪些方法進行增強。
      屬性:
      expression:用於定義切入點表達式。
      id:用於給切入點表達式提供一個唯一標識
    <aop:pointcut expression="execution(
    	public void com.itheima.service.impl.AccountServiceImpl.transfer(
        	java.lang.String, java.lang.String, java.lang.Float)
            )" id="pt1"/> 
    
  • 第五步:使用 aop:xxx 配置對應的通知類型

    • aop:before
      作用:
      用於配置前置通知。指定增強的方法在切入點方法之前執行
      屬性:
      method:用於指定通知類中的增強方法名稱
      ponitcut-ref:用於指定切入點的表達式的引用
      poinitcut:用於指定切入點表達式
      執行時間點:
      切入點方法執行之前執行
    • aop:after-returning
      作用:
      用於配置後置通知
      屬性:
      method:指定通知中方法的名稱。
      pointct:定義切入點表達式
      pointcut-ref:指定切入點表達式的引用
      執行時間點:
      切入點方法正常執行之後。它和異常通知只能有一個執行
    • aop:after-throwing
      作用:
      用於配置異常通知
      屬性:
      method:指定通知中方法的名稱。
      pointct:定義切入點表達式
      pointcut-ref:指定切入點表達式的引用
      執行時間點:
      切入點方法執行產生異常後執行。它和後置通知只能執行一個
    • aop:after
      作用:
      用於配置最終通知
      屬性:
      method:指定通知中方法的名稱。
      pointct:定義切入點表達式
      pointcut-ref:指定切入點表達式的引用
      執行時間點:
      無論切入點方法執行時是否有異常,它都會在其後面執行。
    <aop:before method="beginTransaction" pointcut-ref="pt1"/> 
    
    <aop:after-returning method="commit" pointcut-ref="pt1"/> 
    
    <aop:after-throwing method="rollback" pointcut-ref="pt1"/> 
     
    <aop:after method="release" pointcut-ref="pt1"/> 
    

基於註解的AOP配置

環境搭建

  • 第一步:準備必要的代碼和 jar包

  • 第二步:在配置文件中導入 context 的名稱空間

    <?xml version="1.0" encoding="UTF-8"?> 
    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:context="http://www.springframework.org/schema/context"
     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
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context.xsd"> 
     
     <!-- 配置數據庫操作對象 -->
     <bean id="dbAssit" class="com.dbassit.DBAssit">   
     	<property name="dataSource" ref="dataSource"></property> 
     <!-- 指定 connection 和線程綁定 -->   
     	<property name="useCurrentConnection" value="true"></property>  
     </bean>   
     <!-- 配置數據源 -->
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 
      	<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>  
      </bean> 
    </beans>
    
  • 第三步:把資源使用註解配置

    //賬戶的業務層實現類
    @Service("accountService") 
    public class AccountServiceImpl implements IAccountService {
    	@Autowired  
    	private IAccountDao accountDao;
        }
    //賬戶的持久層實現類
    @Repository("accountDao") 
    public class AccountDaoImpl  implements IAccountDao {
    	@Autowired  
    	private DBAssit dbAssit ; 
    	} 
    
  • 第四步:在配置文件中指定 spring 要掃描的包

    <!-- 告知 spring,在創建容器時要掃描的包 --> 
    <context:component-scan base-package="com.seafy"></context:component-scan>  
    

配置步驟

  • 第一步:把通知類也使用註解配置

    //事務控制類
    @Component("txManager") 
    public class TransactionManager { 
     	//定義一個 DBAssit  
     	@Autowired  private DBAssit dbAssit ;  
     }
    
  • 第二步:在通知類上使用@Aspect 註解聲明爲切面

    • 作用:把當前類聲明爲切面類

      @Aspect//表明當前類是一個切面類 
      public class TransactionManager {   
       //定義一個 DBAssit  
       	@Autowired  private DBAssit dbAssit ; 
       } 
      
  • 第三步:在增強的方法上使用註解配置通知

    • @Before
      作用:
      把當前方法看成是前置通知。
      屬性:
      value:用於指定切入點表達式,還可以指定切入點表達式的引用。
    • @AfterReturning
      作用:
      把當前方法看成是後置通知。
      屬性:
      value:用於指定切入點表達式,還可以指定切入點表達式的引用
    • @AfterThrowing
      作用:
      把當前方法看成是異常通知。
      屬性:
      value:用於指定切入點表達式,還可以指定切入點表達式的引用
    • @After
      作用:
      把當前方法看成是最終通知。
      屬性:
      value:用於指定切入點表達式,還可以指定切入點表達式的引用
     //開啓事務  
    @Before("execution(* com.itheima.service.impl.*.*(..))")  
    public void beginTransaction() {
    	try {
        	dbAssit.getCurrentConnection().setAutoCommit(false);   
        	} catch (SQLException e) {
            	e.printStackTrace();   
            }  
         }
     //提交事務  
    @AfterReturning("execution(* com.itheima.service.impl.*.*(..))")  
    public void commit() {
     	try {    
     		dbAssit.getCurrentConnection().commit();   
     		} catch (SQLException e) {
            	e.printStackTrace();   
            } 
    	}
     //回滾事務  
    @AfterThrowing("execution(* com.itheima.service.impl.*.*(..))")  
    public void rollback() {
    	try {
        	dbAssit.getCurrentConnection().rollback();   
        	} catch (SQLException e) {
            	e.printStackTrace();   
            }  
         } 
    
     //釋放資源  
    @After("execution(* com.itheima.service.impl.*.*(..))")  
    public void release() {
    	try {    
    		dbAssit.releaseConnection();   
    		} catch (Exception e) {
            	e.printStackTrace();   
            }  
         } 
    
  • 第四步:在 spring 配置文件中開啓 spring 對註解 AOP 的支持

    <!-- 開啓 spring 對註解 AOP 的支持 --> 
    <aop:aspectj-autoproxy/>
    

Spring中的JdbcTemplate

JdbcTemplate概述

  • 它是 spring 框架中提供的一個對象,是對原始 Jdbc API 對象的簡單封裝。spring 框架爲我們提供了很多 的操作模板類。
  • 操作關係型數據的:
    • JdbcTemplate
    • HibernateTemplate
  • 操作 nosql 數據庫的:
    • RedisTemplate
  • 操作消息隊列的:
    • JmsTemplate

JdbcTemplate對象的創建

 public JdbcTemplate() {
 } 
 
 public JdbcTemplate(DataSource dataSource) {
 	setDataSource(dataSource); 
  	afterPropertiesSet();  
 } 
 
 public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
 	setDataSource(dataSource);
 	setLazyInit(lazyInit);   
 	afterPropertiesSet();  
 }

JdbcTemplate的增刪改查操作

  • 在 spring 配置文件中配置 JdbcTemplate

    <?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"> 
     
     <!-- 配置一個數據庫的操作模板:JdbcTemplate -->  
     	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        	<property name="dataSource" ref="dataSource"></property>  
        </bean>   
     <!-- 配置數據源 -->  
     	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
     		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
     		<property name="url" value="jdbc:mysql:///spring_day02"></property>  
     		<property name="username" value="root"></property>  
     		<property name="password" value="1234"></property> 
    	</bean> 
    </beans> 
    
  • 最基本使用

    public class JdbcTemplateDemo2 {
    	public static void main(String[] args) {
        	//1.獲取 Spring 容器   
        	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
      		//2.根據 id 獲取 bean 對象   
      		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
      		//3.執行操作   
      		jt.execute("insert into account(name,money)values('eee',500)");  
      		} 
      } 
    
  • 保存操作

    public class JdbcTemplateDemo3 {
    	public static void main(String[] args) { 
     		//1.獲取 Spring 容器   
     		ApplicationContext ac = new 		
     		ClassPathXmlApplicationContext("bean.xml"); 
      		//2.根據 id 獲取 bean 對象   
      		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
      		//3.執行操作   
      		//保存   
      		jt.update("insert into account(name,money)values(?,?)","fff",5000);  
      		} 
      	}
    
  • 更新操作

    public class JdbcTemplateDemo3 {
    	public static void main(String[] args) { 
     
      	//1.獲取 Spring 容器   
      	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
      	//2.根據 id 獲取 bean 對象   
      	JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
      	//3.執行操作   
      	//修改   
      	jt.update("update account set money = money-? where id = ?",300,6); 
     	} 
     } 
    
  • 刪除操作

    public class JdbcTemplateDemo3 {
    	public static void main(String[] args) { 
     
      	//1.獲取 Spring 容器   
      	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
      	//2.根據 id 獲取 bean 對象   
      	JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
      	//3.執行操作   
      	//刪除   
      	jt.update("delete from account where id = ?",6);  
      	}
      }
    
  • 查詢所有操作

    public class JdbcTemplateDemo3 {
    	public static void main(String[] args) { 
     
      	//1.獲取 Spring 容器   
      	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); 
      	//2.根據 id 獲取 bean 對象   
      	JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
      	//3.執行操作   
      	//查詢所有   
      	List<Account> accounts = jt.query("select * from account where money > ? ",             new AccountRowMapper(), 500);   
      		for(Account o : accounts){    System.out.println(o);   
      		} 
     	}
     } 
     
    public class AccountRowMapper implements RowMapper<Account>{
    	@Override  public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        	Account account = new Account();   
        	account.setId(rs.getInt("id"));
            account.setName(rs.getString("name")); 
      		account.setMoney(rs.getFloat("money"));   
      		return account;  
      }
    
  • 查詢一個操作

    //使用 RowMapper 的方式:常用的方式 
    public class JdbcTemplateDemo3 {
    	public static void main(String[] args) { 
     
      	//1.獲取 Spring 容器   
      	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");   		//2.根據 id 獲取 bean 對象   
      	JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
      	//3.執行操作   
      	//查詢一個   
      	List<Account> as = jt.query("select * from account where id = ? ",            	new AccountRowMapper(), 55); 
      		System.out.println(as.isEmpty()?"沒有結果":as.get(0));  
      	} 
    } 
     
    //使用 ResultSetExtractor 的方式:不常用的方式 
    public class JdbcTemplateDemo3 {  
    	public static void main(String[] args) { 
     
      	//1.獲取 Spring 容器   
      	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");   		//2.根據 id 獲取 bean 對象   
      	JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
      	//3.執行操作   
      	//查詢一個   
        Account account = jt.query("select * from account where id = ?",          		new AccountResultSetExtractor(),3);   
        	System.out.println(account);  
        	} 
       }
    
  • 查詢返回一行一列操作

    public class JdbcTemplateDemo3 {
    	public static void main(String[] args) { 
      		//1.獲取 Spring 容器   
      		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");   		//2.根據 id 獲取 bean 對象
      		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); 
      		//3.執行操作   
      		//查詢返回一行一列:使用聚合函數,在不使用 group by 字句時,都是返回一行一列。最長用的 就是分頁中獲取總記錄條數   
      		Integer total = jt.queryForObject("select count(*) from account where money > ? ",Integer.class,500);   
      			System.out.println(total);  
      	} 
    }
    

Spring中的事務控制

Spring中事務控制的API介紹

  • PlatformTransactionManager
    • 此接口是 spring 的事務管理器,它裏面提供了我們常用的操作事務的方法
      • 獲取事務狀態信息
        • TransactionStatus getTransaction(TransactionDefinition definition)
      • 提交事務
        • void commit(TransactionStatus status)
      • 回滾事務
        • void rollback(TransactionStatus status)
  • TransactionDefinition
    • 它是事務的定義信息對象
      • 獲取事務對象名稱
        • String getName()
      • 獲取事務隔離級
        • int getlsolationLevel()
      • 獲取事務傳播行爲
        • int getPropagationBehavior()
      • 獲取事務超時時間
        • int getTimeout()
      • 獲取事務是否只讀
        • boolean isReadOnly()
  • TransactionStatus
    • 此接口提供的是事務具體的運行狀態
    • TransactionStatus接口描述了摸個時間點上事務對象的狀態信息,包含6個具體操作
      • 刷新事務
        • void flush()
      • 獲取是否存在存儲點
        • boolean hasSavepoint()
      • 獲取事務是否完成
        • boolean isCompleted()
      • 獲取事務是否爲新的事務
        • boolean isNewTransaction()
      • 獲取事務是否回滾
        • boolean isRollbackOnly()
      • 獲取事務回滾
        • void setRollbackOnly()

基於XML的聲明式事務控制

環境搭建

  • 第一步:拷貝必要的 jar 包到工程的 lib 目錄
  • 第二步:創建 spring 的配置文件並導入約束
  • 第三步:準備數據庫表和實體類
  • 第四步:編寫業務層接口和實現類
  • 第五步:編寫 Dao 接口和實現類
  • 第六步:在配置文件中配置業務層和持久層對

配置步驟

  • 第一步:配置事務管理器
  • 第二步:配置事務的通知引用事務管理器
  • 第三步:配置事務的屬性
  • 第四步:配置 AOP 切入點表達式
  • 第五步:配置切入點表達式和事務通知的對應關係

基於註解的配置方式

環境搭建

  • 第一步:拷貝必備的 jar 包到工程的 lib 目錄

  • 第二步:創建 spring 的配置文件導入約束並配置掃描的包

  • 第三步:創建數據庫表和實體類

  • 第四步:創建業務層接口和實現類並使用註解讓 spring 管理

    /** 
     * 賬戶的業務層實現類  
     */ 
     @Service("accountService") 
     public class AccountServiceImpl implements IAccountService {
     	@Autowired  
     	private IAccountDao accountDao; 
     
     //其餘代碼和基於 XML 的配置相同 }
    
  • 第五步:創建 Dao 接口和實現類並使用註解讓 spring 管理

    /** 
     * 賬戶的持久層實現類  
     */ 
     @Repository("accountDao") 
     public class AccountDaoImpl implements IAccountDao { 
     
     	@Autowired
        private JdbcTemplate jdbcTemplate;   
     //其餘代碼和基於 XML 的配置相同 
     } 
    

配置步驟

  • 第一步:配置事務管理器並注入數據源

    <!-- 配置事務管理器 -->  
    <bean id="transactionManager" 
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<property name="dataSource" ref="dataSource"></property>  
    </bean> 
    
  • 第二步:在業務層使用@Transactional 註解

    @Service("accountService")
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS) 
    public class AccountServiceImpl implements IAccountService {   
     	@Autowired  
     	private IAccountDao accountDao; 
     
     	@Override  
     	public Account findAccountById(Integer id) {
        	return accountDao.findAccountById(id);  
        } 
     
     	@Override  
     	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)  
     	public void transfer(String sourceName, String targeName, Float money) {
        
      		//1.根據名稱查詢兩個賬戶   
      		Account source = accountDao.findAccountByName(sourceName);   
      		Account target = accountDao.findAccountByName(targeName); 
      		//2.修改兩個賬戶的金額   
      		source.setMoney(source.getMoney()-money);//轉出賬戶減錢
             target.setMoney(target.getMoney()+money);//轉入賬戶加錢   
             //3.更新兩個賬戶   
             accountDao.updateAccount(source);   
             //int i=1/0;
             accountDao.updateAccount(target);
             }
        }
    
  • 第三步:在配置文件中開啓 spring 對註解事務的支持

    <!-- 開啓 spring 對註解事務的支持 --> 
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章