当前位置: 移动技术网 > IT编程>开发语言>Java > Spring AOP AspectJ使用及配置过程解析

Spring AOP AspectJ使用及配置过程解析

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了spring aop aspectj使用及配置过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

aspectj是一个基于java语言的aop框架,spring2.0以后新增了对aspectj切点表达式支持。因为spring1.0的时候aspectj还未出现;

aspectj1.5中新增了对注解的支持,允许直接在bean类中定义切面。新版本的spring框架建
议我们都使用aspectj方式来开发aop,并提供了非常灵活且强大的切点表达式 ;

当然无论使用spring自己的aop还是aspectj相关的概念都是相同的;

注解配置

依赖导入:

<dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-aspects</artifactid>
  <version>5.2.2.release</version>
</dependency>

通知类型

  • @aspectj提供的通知类型:
  • @before 前置通知 在原始方法执行前执行
  • @afterreturning 后置通知 在原始方法执行前执行
  • @around 环绕通知 彻底拦截原始方法的执行,执行前后都可以增加逻辑,也可以不执行原始方法
  • @afterthrowing抛出通知,执行原始方法出现异常时执行
  • @after 最终final通知,不管是否异常,原始方法调用后都会执行
  • @declareparents 引介通知,相当于introductioninterceptor (了解即可)

定义切点

通过execution函数来定义切点

语法:execution(访问修饰符 返回类型 方法名 参数 异常)

表达式示例:

  • 匹配所有类public方法:execution(public * *(..))第一个*表示返回值 ..表示任意个任意类型参数
  • 匹配指定包下所有方法: execution(* cn.xxx.dao.*(..)) 第一个想*表示忽略权限和返回值类型
  • 匹配指定包下所有方法:execution(* cn.xxx.dao..*(..))包含子包
  • 匹配指定类所有方法: execution(* cn.xxx.service.userservice.*(..))
  • 匹配实现特定接口所有类方法 : execution(* cn.xxx.dao.genericdao+.*(..))
  • 匹配所有save开头的方法: execution(* save*(..))

前置通知

pom依赖:

  <dependencies>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-context</artifactid>
      <version>5.2.2.release</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-aspects</artifactid>
      <version>5.2.2.release</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-test</artifactid>
      <version>5.2.2.release</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-test</artifactid>
      <version>5.2.2.release</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupid>junit</groupid>
      <artifactid>junit</artifactid>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

xml需要添加aop名称空间及xsd:

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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">
<!--  启用aspectj  -->
  <aop:aspectj-autoproxy/>
<!--  目标-->
  <bean id="persondao" class="com.yh.demo1.persondao"/>
<!--  切面-->
  <bean class="com.yh.demo1.myaspect"/>
</beans>

test:

@runwith(springjunit4classrunner.class)
@contextconfiguration("classpath:applicationcontext.xml")
public class test1 {
  @autowired
  persondao persondao;

  @test
  public void test(){
    persondao.delete();
    persondao.update();
  }
}

切面类:

import org.aspectj.lang.annotation.aspect;
import org.aspectj.lang.annotation.before;

@aspect
public class myaspect {
   //表示persondao下所有方法都作为切点
  @before(value = "execution(* com.yh.demo1.persondao.*(..))")
  public void beforeadvice(){
    system.out.println("before code run.....");
  }
}

当我们需要获取切点信息(被增强的代码)时,可以在通知添加参数,想下面这样

@aspect
public class myaspect {
  @before(value = "execution(* com.yh.demo1.persondao.*(..))")
  public void beforeadvice2(joinpoint point){
    system.out.println("before code run2....." + point);
  }
}

后置通知:

//当需要获取原始方法的返回值时可以在注解中添加returning参数来指定参数名 aspectj会自动将返回值放到参数中
@afterreturning(value = "execution(* com.yh.demo1.persondao.delete(..))",returning = "result")
public void afteradvice(object result){
  system.out.println("删除方法执行后 .....  返回值为:"+ result);
}

后置通知可以获取目标方法的返回值

环绕通知:

@around(value = "execution(* com.yh.demo1.persondao.insert(..))")
public void aroundadvice(proceedingjoinpoint point) throws throwable {
  //code............
  system.out.println("环绕前置..");

  //执行原始方法 __当需要获取返回值时可以声明变量接收
  object result = point.proceed();
  system.out.println("原始方法返回值: "+result);
  //code............
  system.out.println("环绕后置..");
}

环绕通知与其他通知最大的区别在于环绕通知可以控制是否调用原始方法

注意:参数类型必须为proceedingjoinpoint,否则 无法执行原始方法,

异常通知

@afterthrowing(value = "execution(* com.yh.demo1.persondao.save(..))",throwing = "e")
public void exceptionhandler(joinpoint point,exception e){
  system.out.println(point + " 方法出现"+e.getmessage()+"异常");
}

当方法中出现时才会执行该通知,若需要获取异常信息,可在注解中添加throwing指定参数名称

我们可以使用环绕+异常通知来处理数据库事务,在环绕中开启事务以及提交事务,异常通知中回滚事务,当然spring已经对事务进行了封装不需要自己写

最终通知

@after(value = "execution(* *delete(..))")
public void afterrun(){
  system.out.println("最终");
}

最终通知叫做after 即调用原始方法之后执行无论原始方法中是否出现异常

而后置叫做afterreturning表示在成功返回后才会执行执行

带有逻辑符的表达式:
在表达式中可以使用户逻辑操运算符,与&& 或|| 非!

示例:

/*
execution(* cn.xxx.service.userdao.insert(..))||execution(* cn.xxx.service.userdao.delete(..))

execution(* cn.xxx.service.userdao.*nsert(..))&&execution(* cn.xxx.service.userdao.inser*(..))

!execution(* cn.xxx.service.userdao.insert(..))
*/
2|4切点命名

切点命名

假设有多个通知应用在同一个切点上时,我们需要重复编写execution表达式,且后续要修改切点时则多个通知都需要修改,维护起来非常麻烦,我们可以通过给切点指定名称从而完成对切点的重复使用和统一操作,以提高开发维护效率;

//定义命名切点 方法名称即切点名称
@pointcut(value = "execution(* com.yh.demo1.persondao.save(..))")
private void savepointcut(){}

@pointcut(value = "execution(* com.yh.demo1.persondao.delete(..))")
private void deletepointcut(){}

多个通知应用到同一个切点:

//使用命名切点
@before(value = "savepointcut()")
public void beforeadvice(){
  system.out.println("before code run.....");
}
//使用命名切点
@around(value = "savepointcut()")
public void beforeadvice2(proceedingjoinpoint point) throws throwable {
  system.out.println("环绕前");
  point.proceed();
  system.out.println("环绕后");

一个通知应用到多个切点

//同一个通知对应多个切点
@after(value = "savepointcut()||deletepointcut()")
public void afteradvice(){
  system.out.println("after code run.....");
}

xml配置

xml配置所需的jar 以及各个对象之间的依赖关以及表达式的写法都是一样的,仅仅是换种方式来写而已;

xml:

    <!--目标-->
  <bean id="studentdao" class="com.yh.demo2.studentdao"/>
    <!--通知-->
  <bean id="advices" class="com.yh.demo2.xmladvice"/>

    <!--织入信息-->
  <aop:config>
        <!--切点定义-->
    <aop:pointcut id="select" expression="execution(* com.yh.demo2.studentdao.select(..))"/>
        <!--切面定义-->
    <aop:aspect ref="advices">
      <aop:before method="before" pointcut-ref="select"/>
      <aop:after-returning method="afterreturning" pointcut-ref="select" returning="result"/>
      <aop:after method="after" pointcut-ref="select" />
      <aop:after-throwing method="exception" pointcut-ref="select" throwing="e"/>
      <aop:around method="around" pointcut-ref="select"/>
    </aop:aspect>
   
    <!--入侵式通知 即通知需要实现指定接口 两种不能同时使用 -->
    <aop:advisor advice-ref="advice2" pointcut-ref="select"/>
  </aop:config>
 <!--入侵式通知bean-->
 <bean id="advice2" class="com.yh.demo2.xmladvice2"/>

通知类:

import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.joinpoint;

public class xmladvice {
  public void before(joinpoint pointcut){ system.out.println("前置通知 切点:"+pointcut); }

  public void afterreturning(joinpoint point,object result){
    system.out.println("后置通知 切点:"+point);
  }

  public void after(joinpoint point){ system.out.println("最终通知 切点:"+point); }

  public void exception(joinpoint point,throwable e){
    system.out.println("异常通知: " + e+"切点:"+point);
  }

  public void around(proceedingjoinpoint point) throws throwable {
    system.out.println("环绕前");
    point.proceed();
    system.out.println("环绕后");
  }
}

你会发现 ,无论是xml还是注解都不需要手动指定代理,以及目标对象,aspectj会从切点中获取目标对象信息并自动创建代理;

aspectj是目前更流行的方式,具体采用xml还是注解需要根据项目具体情况,小组协作开发推荐xml;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网