Spring之AOP使用xml配置更方便(使用AspectJ框架)(重点)

来源:互联网 发布:少儿编程前景 编辑:程序博客网 时间:2024/06/16 11:02

Spring的AOP的实现是使用AspectJ框架实现的,导入AspectJ的jar包。AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码(性能监视、事务管理、安全检查、缓存)

(一)AOP术语

     Joinpoint(连接点):可以被拦截的方法。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点.
  Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义.
  Advice(通知/增强):(方法级别)所谓通知是指拦截到Joinpoint方法之后所要添加的逻辑.通知分为前置通知,后置通知,异常通知,最终通知,环绕通知(切面要完成的功能)
  Introduction(引介):(类级别)引介是一种特殊的通知在不修改类代码的前提下, Introduction可以在运行期为类动态地添加一些方法或Field.
  Target(目标对象):代理的目标对象
  Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程.spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入
  Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类。(代理对象)
  Aspect(切面): 是切入点和通知(引介)的组合

(二)基于注解方式的配置 

1、AspectJ表达式:

    语法:execution(表达式)
      execution(<访问修饰符>?<返回类型><方法名>(<参数>)<异常>)

      execution(“* cn.itcast.spring3.demo1.dao.*(..)”) ---只检索当前包
      execution(“* cn.itcast.spring3.demo1.dao..*(..)”) ---检索包及当前包的子包.
      execution(* cn.itcast.dao.GenericDAO+.*(..)) ---检索GenericDAO及子类

execution(public * com.bjsxt.service..*.*(..))    ---表示service包以及子包的任何方法,返回类型任意

  AspectJ增强
    @Before 前置通知,相当于BeforeAdvice
    @AfterReturning 后置通知,相当于AfterReturningAdvice
    @Around 环绕通知,相当于MethodInterceptor
    @AfterThrowing抛出通知,相当于ThrowAdvice
    @After 最终final通知,不管是否异常,该通知都会执行
    @DeclareParents 引介通知,相当于IntroductionInterceptor (不要求掌握)

  基于注解开发
    第一步:引入相应jar包
      aspectj依赖aop环境
      spring-aspects-3.2.0.RELEASE.jar
      com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

    第二步:编写被增强的类:

public class UserDao {    public void add(){        System.out.println("添加用户");    }    public int update(){        System.out.println("修改用户");        return 1;    }    public void delete(){        System.out.println("删除用户");    }    public void find(){        System.out.println("查询用户");        //int d = 1/ 0;    }}

    第三步:使用AspectJ注解形式

@Aspectpublic class MyAspect {       @Before("execution(* cn.itcast.spring3.demo1.UserDao.add(..))")    public void before(JoinPoint joinPoint){        System.out.println("前置增强...."+joinPoint);    }       @AfterReturning(value="execution(* cn.itcast.spring3.demo1.UserDao.update(..))",returning="returnVal")    public void afterReturin(Object returnVal){        System.out.println("后置增强....方法的返回值:"+returnVal);    }      @Around(value="MyAspect.myPointcut()")    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{        System.out.println("环绕前增强....");        Object obj = proceedingJoinPoint.proceed();        System.out.println("环绕后增强....");        return obj;    }      @AfterThrowing(value="MyAspect.myPointcut()",throwing="e")    public void afterThrowing(Throwable e){        System.out.println("不好了 出异常了!!!"+e.getMessage());    }     @After("MyAspect.myPointcut()")    public void after(){        System.out.println("最终通知...");    }     @Pointcut("execution(* cn.itcast.spring3.demo1.UserDao.find(..))")//切点的定义    private void myPointcut(){}}

    第四步:创建applicationContext.xml

<?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
"> <!-- 自动生成代理 底层就是AnnotationAwareAspectJAutoProxyCreator --> <aop:aspectj-autoproxy /> <bean id="userDao" class="cn.yzu.spring3.demo1.UserDao"></bean> <bean id="myAspect" class="cn.yzu.spring3.demo1.MyAspect"></bean></beans>

    第五步:测试

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class SpringTest1 {    @Autowired    @Qualifier("userDao")    private UserDao userDao;     @Test    public void demo1(){        userDao.add();        userDao.delete();        userDao.update();        userDao.find();        /**         * 输出:             *  前置增强....execution(void cn.itcast.spring3.demo1.UserDao.add())                添加用户                删除用户                修改用户                后置增强....方法的返回值:1                环绕前增强....                查询用户                环绕后增强....                最终通知...         */    }}


(三)基于xml的配置方式:

 第一步:编写被增强的类:

复制代码
public class ProductDao {    public int add(){        System.out.println("添加商品...");        //int d = 10/0;        return 100;    }    public void update(){        System.out.println("修改商品...");    }    public void delete(){        System.out.println("删除商品...");    }    public void find(){        System.out.println("查询商品...");    }}
复制代码

    第二步:定义切面

复制代码
public class MyAspectXML {    public void before(){        System.out.println("前置通知...");    }    public void afterReturing(Object returnVal){        System.out.println("后置通知...返回值:"+returnVal);    }    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{        System.out.println("环绕前增强....");        Object result = proceedingJoinPoint.proceed();        System.out.println("环绕后增强....");        return result;    }    public void afterThrowing(Throwable e){        System.out.println("异常通知..."+e.getMessage());    }    public void after(){        System.out.println("最终通知....");    }}
复制代码

    第三步:配置applicationContext.xml

复制代码
<?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"
> <!-- 定义被增强的类 --> <bean id="productDao" class="cn.yzu.spring3.demo2.ProductDao"></bean> <!-- 定义切面 --> <bean id="myAspectXML" class="cn.yzu.spring3.demo2.MyAspectXML"></bean> <!-- 定义aop配置 可以在xml的design模式下配置--> <aop:config> <!-- 定义切点(全局的): --> <aop:pointcut expression="execution(* cn.itcast.spring3.demo2.ProductDao.add(..))" id="mypointcut"/> <aop:aspect ref="myAspectXML"> <!-- 前置通知 --> <!-- <aop:before method="before" pointcut-ref="mypointcut"/> --> <!-- 后置通知 --> <!-- <aop:after-returning method="afterReturing" pointcut-ref="mypointcut" returning="returnVal"/> --> <!-- 环绕通知 --> <!-- <aop:around method="around" pointcut-ref="mypointcut"/> --> <!-- 异常通知 --> <!-- <aop:after-throwing method="afterThrowing" pointcut-ref="mypointcut" throwing="e"/> --> <!-- 最终通知 --> <aop:after method="after" pointcut-ref="mypointcut"/> </aop:aspect> </aop:config></beans>
 <!-- 切点也可以定义在切面内: -->
<aop:config>
<aop:aspect id="logAspect" ref="logInterceptor">
<aop:before method="before" pointcut="execution(public * com.bjsxt.service..*.add(..))" />
</aop:aspect>
</aop:config>

注意:<aop:advisor>和<aop:aspect>的区别:advisor只持有一个Pointcut和一个advice,而aspect可以多个pointcut和多个advice

注意:
1.环绕方法通知,环绕方法通知要注意必须给出调用之后的返回值,否则被代理的方法会停止调用并返回null,除非你真的打算这么做。           
2.只有环绕通知才可以使用JoinPoint的子类ProceedingJoinPoint,各连接点类型可以调用代理的方法,并获取、改变返回值。


(一)JoinPoint:连接点:可以获取目标方法的名字和传入参数

  1. 连接点(JoinPoint) 这个就更好解释了,就是spring允许你是通知(Advice)的地方,那可就真多了,基本每个方法的钱、后(两者都有也行),或抛出异常是时都可以是连接点,spring只支持方法连接点。其他如AspectJ还可以让你在构造器或属性注入时都行,不过那不是咱们关注的,只要记住,和方法有关的前前后后都是连接点。
  2. 切入点(Pointcut) 上面说的连接点的基础上,来定义切入点,你的一个类里,有15个方法,那就有十几个连接点了对吧,但是你并不想在所有方法附件都使用通知(使用叫织入,下面再说),你只是想让其中几个,在调用这几个方法之前、之后或者抛出异常时干点什么,那么就用切入点来定义这几个方法,让切点来筛选连接点,选中那几个你想要的方法。

AspectJ使用org.aspectj.lang.JoinPoint接口表示目标类连接点对象,如果是环绕增强时,使用org.aspectj.lang.ProceedingJoinPoint表示连接点对象,该类是JoinPoint的子接口。任何一个增强方法都可以通过将第一个入参声明为JoinPoint访问到连接点上下文的信息。我们先来了解一下这两个接口的主要方法: 
1)JoinPoint 
 java.lang.Object[] getArgs():获取连接点方法运行时的入参列表; 
 Signature getSignature() :获取连接点的方法签名对象; 
 java.lang.Object getTarget() :获取连接点所在的目标对象; 
 java.lang.Object getThis() :获取代理对象本身; 
2)ProceedingJoinPoint 
ProceedingJoinPoint继承JoinPoint子接口,它新增了两个用于执行连接点方法的方法: 
 java.lang.Object proceed() throws java.lang.Throwable:通过反射执行目标对象的连接点处的方法; 
 java.lang.Object proceed(java.lang.Object[] args) throws java.lang.Throwable:通过反射执行目标对象连接点处的方法,不过使用新的入参替换原来的入参。 

补充:
1.<aop:pointcut>如果位于<aop:aspect>元素中,则命名切点只能被当前<aop:aspect>内定义的元素访问到,为了能被整个<aop:config>元素中定义的所有增强访问,则必须在<aop:config>下定义切点。
2.如果在<aop:config>元素下直接定义<aop:pointcut>,必须保证<aop:pointcut>在<aop:aspect>之前定义。<aop:config>下还可以定义<aop:advisor>,三者在<aop:config>中的配置有先后顺序的要求:首先必须是<aop:pointcut>,然后是<aop:advisor>,最后是<aop:aspect>。而在<aop:aspect>中定义的<aop:pointcut>则没有先后顺序的要求,可以在任何位置定义。
.<aop:pointcut>:用来定义切入点,该切入点可以重用;
.<aop:advisor>:用来定义只有一个通知和一个切入点的切面
.<aop:aspect>:用来定义切面,该切面可以包含多个切入点和通知,而且标签内部的通知和切入点定义是无序的;和advisor的区别就在此,advisor只包含一个通知和一个切入点。
3.在使用spring框架配置AOP的时候,不管是通过XML配置文件还是注解的方式都需要定义pointcut"切入点"
例如定义切入点表达式 execution(* com.sample.service.impl..*.*(..))
execution()是最常用的切点函数,其语法如下所示:
整个表达式可以分为五个部分:
(1)、execution(): 表达式主体。
(2)、第一个*号:表示返回类型,*号表示所有的类型。
(3)、包名:表示需要拦截的包名,后面的两个句点表示当前包和当前包的所有子包,com.sample.service.impl包、子孙包下所有类的方法。
(4)、第二个*号:表示类名,*号表示所有的类。
(5)、*(..):最后这个星号表示方法名,*号表示所有的方法,后面括弧里面表示方法的参数,两个句点表示任何参数。


    

第四步:测试

复制代码
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext2.xml")public class SpringTest2 {    @Autowired    @Qualifier("productDao")    private ProductDao productDao;        @Test    public void demo1(){        productDao.add();        productDao.find();        productDao.update();        productDao.delete();        /**         * 输出:         *  添加商品...            最终通知....            查询商品...            修改商品...            删除商品...         */    }}

aop的配置:

<aop:config>
<aop:aspect id="logAspect" ref="logInterceptor">
<aop:before method="before" pointcut="execution(public * com.bjsxt.service..*.add(..))" />
</aop:aspect>
</aop:config>

aspect:由pointcut和advice组成。pointcut:被拦截的方法。


问题一:

args是和execution用在一起,用来过滤要被代理的方法的,如果不和arg-names一起用,那么用法是args(类名,类名...)。 如果和arg-names(参数名1,参数名2...)一起用,那么用法是args(参数1,参数2...),其中,参数1和参数2的类型由arg-names所代表的方法的参数确定

arg-names是和代理方法一起用的(就是你要加在被代理的方法之前或者之后的那个方法) arg-names(参数名1,参数名2...) 其中的参数名1 参数名2 和 代理方法的参数名是一一对应的

通过"argNames"属性指定参数名。

[html] view plain copy
  1. @Before(value="args(param)"argNames="param") //明确指定了    
  2. public void beforeTest(String param) {    
  3.     System.out.println("param:" + param);    
  4. }  

args、argNames的参数名与beforeTest()方法中参数名 保持一致,即param


问题二:


但如果 cn.xxxx..*.* 的方法有多个参数,且个数不定,要想让切点可以切入,这么个写法就不行了。 

我搜了N多的帖子,也没能找到方法,最终几经辗转,终于在网友的帮助下,点破了这一层窗户纸,其实也很简单,还是在配置的写法: args(..)表示:匹配更多的参数。

Xml代码  收藏代码
  1. <aop:before method="before" pointcut="execution(* cn.xxxx..*.*(..)) and args(..)"/>    

与之配合的切点的写法是 
Java代码  收藏代码
  1. public void before(JoinPoint jp) throws Throwable {  
  2. ...  
  3. }  

这样,不论业务Bean的方法有多少个参数,都可以被这个切点切入了。如果需要访问各个参数,只需 
Java代码  收藏代码
  1. Object[] args = jp.getArgs();  


通过两个问题可以得出args的作用:


使用 args表达式 有如下两个作用:

① 提供了一种简单的方式来访问目标方法的参数。即:切入点将只匹配具有对应形参的方法,且目标方法的参数值将被传入增强处理方法中。

② 可用于对切入表达式增加额外的限制。


参考文档:http://blog.csdn.net/confirmaname/article/details/9739899


参考文档:

https://www.cnblogs.com/xiaoxi/p/5981514.html

https://www.cnblogs.com/best/p/5736422.html

原创粉丝点击