Spring-Aop详细教程

问题?SpringAop的定义及使用

Aop定义:

aop:

   1、切面

        事务、日志、安全性框架、权限等都是切面

   2、通知

      切面中的方法就是通知

   3、目标类

   4、切入点

         只有符合切入点,才能让通知和目标方法结合在一起

   5、织入:

         形成代理对象的方法的过程

         

 

好处:

   事务、日志、安全性框架、权限、目标方法之间完全是松耦合的



execution详解:



executionpublic * *..)) 所有的公共方法

execution(*set*..)) 以set开头的任意方法

execution(*com.xyz.service.AccountService.*..))com.xyz.service.AccountService类中的所有的方法

execution(*com.xyz.service.*.*..)) com.xyz.service包中的所有的类的所有的方法

execution(*com.xyz.service..*.*..))com.xyz.service包及子包中所有的类的所有的方法

execution(*cn.itcast.spring.sh..*.*(String,?,Integer)) cn.itcast.spring.sh包及子包中所有的类的有三个参数

                                                           第一个参数为String,第二个参数为任意类型,

                                                           第三个参数为Integer类型的方法


加载过程:

springAOP的具体加载步骤:

   1、当spring容器启动的时候,加载了spring的配置文件

   2、为配置文件中所有的bean创建对象

   3spring容器会解析aop:config的配置

       1、解析切入点表达式,用切入点表达式和纳入spring容器中的bean做匹配

            如果匹配成功,则会为该bean创建代理对象,代理对象的方法=目标方法+通知

            如果匹配不成功,不会创建代理对象

   4、在客户端利用context.getBean获取对象时,如果该对象有代理对象则返回代理对象,如果代理对象,则返回目标对象

说明:如果目标类没有实现接口,则spring容器会采用cglib的方式产生代理对象,如果实现了接口,会采用jdk的方式


通知:

通知:

   1、前置通知

      1、在目标方法执行之前执行

      2、无论目标方法是否抛出异常,都执行,因为在执行前置通知的时候,目标方法还没有执行,还没有遇到异常

   2、后置通知

      1、在目标方法执行之后执行

      2、当目标方法遇到异常,后置通知将不再执行

      3、后置通知可以接受目标方法的返回值,但是必须注意:

               后置通知的参数的名称和配置文件中returning="var"的值是一致的

   3、最终通知:

      1、在目标方法执行之后执行

      2、无论目标方法是否抛出异常,都执行,因为相当于finally

   4、异常通知

      1、接受目标方法抛出的异常信息

      2、步骤

           在异常通知方法中有一个参数Throwable  ex

           在配置文件中

              <aop:after-throwingmethod="throwingMethod" pointcut-ref="perform"throwing="ex"/>

   5、环绕通知

       1、如果不在环绕通知中调用ProceedingJoinPointproceed,目标方法不会执行

       2、环绕通知可以控制目标方法的执行


联合hibernate+spring的案例:

hibernate工具类:

  1. package cn.itcast.spring.sh.aop;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.Transaction;  
  6. import org.hibernate.cfg.Configuration;  
  7.   
  8. public class HibernateUtils {  
  9.     public static SessionFactory sessionFactory;  
  10.     static{  
  11.         Configuration configuration = new Configuration();  
  12.         configuration.configure("cn/itcast/spring/sh/aop/hibernate.cfg.xml");  
  13.         sessionFactory = configuration.buildSessionFactory();  
  14. //      Session session = sessionFactory.openSession();  
  15. //      Transaction transaction = session.beginTransaction();  
  16. //      transaction.commit();  
  17.     }  
  18. }  


持久化类:

  1. package cn.itcast.spring.sh.aop;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Person implements Serializable{  
  6.     private Long pid;  
  7.     private String pname;  
  8.     private String psex;  
  9.       
  10.     public Person(){}  
  11.       
  12.     public Person(String pname){  
  13.         this.pname = pname;  
  14.     }  
  15.       
  16.     public Long getPid() {  
  17.         return pid;  
  18.     }  
  19.     public void setPid(Long pid) {  
  20.         this.pid = pid;  
  21.     }  
  22.     public String getPname() {  
  23.         return pname;  
  24.     }  
  25.     public void setPname(String pname) {  
  26.         this.pname = pname;  
  27.     }  
  28.     public String getPsex() {  
  29.         return psex;  
  30.     }  
  31.     public void setPsex(String psex) {  
  32.         this.psex = psex;  
  33.     }  
  34.       
  35. }  

映射文件:Person.hbm.xml

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4.   
  5. <hibernate-mapping>  
  6.     <!--   
  7.         用来描述一个持久化类  
  8.         name  类的全名  
  9.         table 可以不写  默认值和类名一样   
  10.         catalog  数据库的名称  一般不写  
  11.      -->  
  12.     <class name="cn.itcast.spring.sh.aop.Person">  
  13.         <!--   
  14.             标示属性  和数据库中的主键对应  
  15.             name  属性的名称  
  16.             column 列的名称  
  17.          -->  
  18.         <id name="pid" column="pid" length="200" type="java.lang.Long">  
  19.             <!--   
  20.                 主键的产生器  
  21.                   就该告诉hibernate容器用什么样的方式产生主键  
  22.              -->  
  23.             <generator class="increment"></generator>  
  24.         </id>  
  25.         <!--  
  26.             描述一般属性 
  27.          -->  
  28.         <property name="pname" column="pname" length="20" type="string"></property>  
  29.           
  30.         <property name="psex" column="psex" length="10" type="java.lang.String"></property>  
  31.     </class>  
  32. </hibernate-mapping>  


hibernate.cfg.xml配置文件

[html]  view plain copy print ?
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5. <hibernate-configuration>  
  6.     <!--  
  7.         一个session-factory只能连接一个数据库 
  8.     -->  
  9. <session-factory>  
  10.     <!--  
  11.         数据库的用户名 
  12.     -->  
  13.     <property name="connection.username">root</property>  
  14.     <!--  
  15.         密码 
  16.     -->  
  17.     <property name="connection.password">root</property>  
  18.     <!--  
  19.         url 
  20.     -->  
  21.     <property name="connection.url">  
  22.         jdbc:mysql://localhost:3306/Use_Aop  
  23.     </property>  
  24.     <!--   
  25.         作用:根据持久化类和映射文件生成表  
  26.         validate  
  27.         create-drop  
  28.         create  
  29.         update  
  30.     -->  
  31.     <property name="hbm2ddl.auto">update</property>  
  32.     <!--  
  33.         显示hibernate内部生成的sql语句 
  34.     -->  
  35.     <property name="show_sql">true</property>  
  36.     <property name="current_session_context_class">thread</property>  
  37.     <!-- 添加映射文件 -->  
  38.     <mapping resource="cn/itcast/spring/sh/aop/Person.hbm.xml" />  
  39.   
  40. </session-factory>  
  41. </hibernate-configuration>  

dao层接口:

[java]  view plain copy print ?
  1. package cn.itcast.spring.sh.aop;  
  2.   
  3. public interface PersonDao {  
  4.     public String savePerson(Person person);  
  5. }  

dao实现层

[java]  view plain copy print ?
  1. package cn.itcast.spring.sh.aop;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. import org.junit.Test;  
  6.   
  7. public class PersonDaoImpl extends HibernateUtils implements PersonDao  {  
  8.   
  9.     public String savePerson(Person person) {  
  10.         //在这里首先得开启事务才能crud操作,Springaop配置已经准备好动态代理了  
  11.         //int a=1/0;  
  12.         sessionFactory.getCurrentSession().save(person);  
  13.         System.out.println("执行保存操作了。");  
  14.         return "aaa";  
  15.     }  
  16.       
  17.   
  18.   
  19. }  

事务层

[java]  view plain copy print ?
  1. package cn.itcast.spring.sh.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.ProceedingJoinPoint;  
  5. import org.hibernate.Transaction;  
  6.   
  7. public class MyTransaction extends HibernateUtils {  
  8.     private Transaction transaction;  
  9.       
  10.     /** 
  11.      * 通过一些参数可以获取目标方法的相关信息,报告目标方法名称、返回值参数、异常信息等 
  12.      * 不过相应的也要在配置文件中进行设置(通过实验,好像只配置后置及异常就可以只用了),不然就获取不了。 
  13.      * 注:环绕通知不可以跟前置通知和后置通知一起用,因为环绕通知已经把两个通知的东西做了,它可以调用目标方法 
  14.      *  
  15.      * */  
  16.       
  17.     public void beginTransaction(JoinPoint joinPoint){  
  18.         //可以通过该参数得到目标方法名称(导的是这个包:import org.aspectj.lang.JoinPoint;)  
  19.         System.out.println(joinPoint.getSignature().getName());  
  20.         //开启事务  
  21.         System.out.println("开启事务");  
  22.         this.transaction = sessionFactory.getCurrentSession().beginTransaction();  
  23.           
  24.     }  
  25.     //这里的var参数是后置通知,得到目标方法的返回值  
  26.     public void commit(Object var){  
  27.         //提交事务  
  28.         this.transaction.commit();  
  29.         System.out.println(var);  
  30.         System.out.println("关闭事务");  
  31.     }  
  32.       
  33.     //测试最终通知  
  34. //  public void finallFun(){  
  35. //      System.out.println("最终通知发生了");  
  36. //  }  
  37.       
  38.     //测试异常通知  
  39.     //throwing="ag":表示异常信息参数,和配置文件中是相对应的  
  40. //  public void exception(Throwable ag){  
  41. //      System.out.println("异常信息:"+ag);  
  42. //  }  
  43.       
  44.     //测试环绕异常通知  
  45. //  public void aroundException(ProceedingJoinPoint joitPoint) throws Throwable{  
  46. //      //joitPoint.proceed();//调用目标方法,不然目标方法不能执行,这个时候前置和后置都已经不用了  
  47. //      System.out.println("环绕通知发生");  
  48. //  }  
  49. }  

spring配置文件(applicationContext.xml):

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:aop="http://www.springframework.org/schema/aop"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">  
  8.   
  9.     <!-- SpringAop案例  
  10.         使用条件:必须有  
  11.         xmlns:aop="http://www.springframework.org/schema/aop"   
  12.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"   
  13.     -->  
  14.       
  15.     <!-- 导入目标类 -->  
  16.     <bean id="personDao" class="cn.itcast.spring.sh.aop.PersonDaoImpl"></bean>  
  17.     <bean id="myTransaction" class="cn.itcast.spring.sh.aop.MyTransaction"></bean>  
  18.     <!-- aop配置 -->  
  19.     <aop:config>  
  20.       <!--  
  21.         切入点表达式 
  22.       -->  
  23.       <aop:pointcut expression="execution(* cn.itcast.spring.sh.aop.PersonDaoImpl.*(..))" id="perform"/>  
  24.       <!--  
  25.       aop:aspect:引入切面  
  26.      前置通知:aop:before:目标方法没执行前执行该方法  
  27.       后置通知:aop:after-returning:目标方法执行后执行该方法。目标方法有异常,不会执行了,  
  28.                 这里的var是后置通知的参数,可以得到目标方法的返回值,并且和方法中所带参数(Object var)一致  
  29.   最终通知::aop:after :表示目标方法执行后才执行,不管目标方法有没有异常,都会执行。  
  30.         异常通知:aop:after-throwing:当目标方法出现错误了,就会执行该方法,throwing="ag":表示异常信息参数,在方法中带参数(Throwable ag)(可以使用  
  31.    环绕通知:aop:around 可以控制目标方法的执行(注:环绕与前置、后置不能一起用.)  
  32.      
  33.       pointcut-ref: 引入切入点  
  34.         returning="var":代表接受目标类方法中的返回值  
  35.        -->  
  36.       <aop:aspect ref="myTransaction">  
  37.             <aop:before method="beginTransaction" pointcut-ref="perform"/>  
  38.             <aop:after-returning method="commit" pointcut-ref="perform" returning="var"/>  
  39.             <!-- <aop:after method="finallFun" pointcut-ref="perform"/>  
  40.             <aop:after-throwing method="exception" throwing="ag" pointcut-ref="perform"/> -->  
  41.             <!-- <aop:around method="aroundException" pointcut-ref="perform"/> -->  
  42.       </aop:aspect>  
  43.     <!--  
  44.     通知类型:  
  45.   
  46.     前置通知(Before advice):在某连接点之前执行的通知,  
  47.                             但这个通知不能阻止连接点之前的执行流程(除非它抛出一个异常)。   
  48.   
  49.     后置通知(After returning advice):在某连接点正常完成后执行的通知:  
  50.                                     例如,一个方法没有抛出任何异常,正常返回。   
  51.   
  52.     异常通知(After throwing advice):在方法抛出异常退出时执行的通知。   
  53.   
  54.     最终通知(After (finally) advice):当某连接点退出的时候执行的通知  
  55.                                     (不论是正常返回还是异常退出)。   
  56.   
  57.     环绕通知(Around Advice):包围一个连接点的通知,如方法调用。  
  58.                             这是最强大的一种通知类型。环绕通知可以在方法调用前后完成自定义的行为。  
  59.                             它也会选择是否继续执行连接点或直接返回它自己的返回值或抛出异常来结束执行。   
  60.        
  61.      -->  
  62. </beans>  

测试类:

[java]  view plain copy print ?
  1. package cn.itcast.spring.sh.aop;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6.   
  7. public class PersonTest {  
  8.     @Test  
  9.     public void test(){  
  10.         ApplicationContext applicationContext = new  ClassPathXmlApplicationContext("cn/itcast/spring/sh/aop/applicationContext.xml");  
  11.         PersonDao personDao = (PersonDao)applicationContext.getBean("personDao");  
  12.         Person person1 = new Person();  
  13.         person1.setPname("李大鹏");  
  14.         person1.setPsex("男");  
  15.         personDao.savePerson(person1);  
  16.     }  
  17. }  
  18. 结果:

    spring动态代理:



    异常信息的执行结果:



    注意:继承接口的是cglib动态代理方式,而在getbean的时候产生的不是接口的对象而是动态代理的对象


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值