spring @Aspect注解

要在 Spring 应用中使用 AspectJ 注解, 必须在 classpath 下包含 AspectJ 类库: aopalliance.jaraspectj.weaver.jar spring-aspects.jar

aop Schema 添加到 <beans> 根元素中.

要在 Spring IOC 容器中启用 AspectJ 注解支持, 只要Bean 配置文件中定义一个空的 XML 元素 <aop:aspectj-autoproxy>

Spring IOC 容器侦测到 Bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理.

要在 Spring 中声明 AspectJ 切面, 只需要在 IOC 容器中将切面声明为 Bean 实例. 当在 Spring IOC 容器中初始化 AspectJ 切面之后, Spring IOC 容器就会为那些与 AspectJ 切面相匹配的 Bean 创建代理.

AspectJ 注解中, 切面只是一个带有 @Aspect 注解的 Java .

通知是标注有某种注解的简单的 Java 方法.

AspectJ 支持 5 种类型的通知注解:

@Before: 前置通知, 在方法执行之前执行

@After: 后置通知, 在方法执行之后执行

@AfterRunning: 返回通知, 在方法返回结果之后执行

@AfterThrowing: 异常通知, 在方法抛出异常之后

@Around: 环绕通知, 围绕着方法执行

主要步骤:

 1. 加入 jar 包
 * com.springsource.net.sf.cglib-2.2.0.jar
 * com.springsource.org.aopalliance-1.0.0.jar
 * com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
 * spring-aspects-4.0.0.RELEASE.jar
 2. 在 Spring 的配置文件中加入 aop 的命名空间。 
 3. 基于注解的方式来使用 AOP
    3.1 在配置文件中配置自动扫描的包: <context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan>
   3.2 加入使 AspjectJ 注解起作用的配置: <aop:aspectj-autoproxy></aop:aspectj-autoproxy>为匹配的类自动生成动态代理对象. 
 4. 编写切面类: 
   4.1 一个一般的 Java 类
   4.2 在其中添加要额外实现的功能. 
5. 配置切面
   5.1 切面必须是 IOC 中的 bean: 实际添加了 @Component 注解
   5.2 声明是一个切面: 添加 @Aspect
   5.3 声明通知: 即额外加入功能对应的方法. 
   5.3.1 前置通知: @Before("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(int, int))")
    @Before 表示在目标方法执行之前执行 @Before 标记的方法的方法体. 
    @Before 里面的是切入点表达式: 
6. 在通知中访问连接细节: 可以在通知方法中添加 JoinPoint 类型的参数, 从中可以访问到方法的签名和方法的参数.
7. @After 表示后置通知: 在方法执行之后执行的代码.

利用方法签名编写 AspectJ 切入点表达式

最典型的切入点表达式时根据方法的签名来匹配各种方法:

execution * com.atguigu.spring.ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中声明的所有方法,第一个 * 代表任意修饰符及任意返回值. 第二个 * 代表任意方法. .. 匹配任意数量的参数. 若目标类与接口与该切面在同一个包中, 可以省略包名.

execution public * ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 接口的所有公有方法.

execution public double ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 返回 double 类型数值的方法

execution public double ArithmeticCalculator.*(double, ..): 匹配第一个参数为 double 类型的方法, .. 匹配任意数量任意类型的参数

execution public double ArithmeticCalculator.*(double, double): 匹配参数类型为 double, double 类型的方法.

合并切入点表达式

AspectJ , 切入点表达式可以通过操作符 &&, ||, ! 结合起来.

让通知访问当前连接点的细节

可以在通知方法中声明一个类型为 JoinPoint 的参数. 然后就能访问链接细节. 如方法名称和参数值.

后置通知

后置通知是在连接点完成之后执行的, 即连接点返回结果或者抛出异常的时候, 下面的后置通知记录了方法的终止.

一个切面可以包括一个或者多个通知.

返回通知

无论连接点是正常返回还是抛出异常, 后置通知都会执行. 如果只想在连接点返回的时候记录日志, 应使用返回通知代替后置通知.

在返回通知中访问连接点的返回值

在返回通知中, 只要将 returning 属性添加到 @AfterReturning 注解中, 就可以访问连接点的返回值. 该属性的值即为用来传入返回值的参数名称.

必须在通知方法的签名中添加一个同名参数. 在运行时, Spring AOP 会通过这个参数传递返回值.

原始的切点表达式需要出现在 pointcut 属性中

异常通知

只在连接点抛出异常时才执行异常通知

throwing 属性添加到 @AfterThrowing 注解中, 也可以访问连接点抛出的异常. Throwable 是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.

如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行.

环绕通知

环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.

对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点.

在环绕通知中需要明确调用 ProceedingJoinPoint proceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.

注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常

例如(采用前置通知):

application.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:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       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
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
">
    <!--配置自动扫描包-->
    <context:component-scan base-package="com.aop"/>
    <aop:aspectj-autoproxy/>

</beans>

Calculator接口

package com.aop;

public interface Calculator {

    int add(int i, int j);
    int sub(int i, int j);
    int mul(int i, int j);

}

LoggingAspect.class

package com.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component("loggingAspect")
public class LoggingAspect {

    @Before("execution(public int com.aop.RealizationCalculator.add(int, int))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        List<Object> list = Arrays.asList(joinPoint.getArgs());
        System.out.println("list#############");
        System.out.println(list);
        System.out.println("methodName############");
        System.out.println(methodName);
        System.out.println("before");
    }

    public void afterMethod(){
        System.out.println("after");
    }
}

RealizationCalculator.class

package com.aop;

import org.springframework.stereotype.Component;

@Component("realizationCalculator")
public class RealizationCalculator implements Calculator {
    @Override
    public int add(int i, int j) {
        System.out.println("add……"+i);
        int result = i+j;
        System.out.println("add……"+result);
        return result;
    }

    @Override
    public int sub(int i, int j) {
        System.out.println("sub……"+i);
        int result = i-j;
        System.out.println("add……"+result);
        return result;
    }

    @Override
    public int mul(int i, int j) {
        System.out.println("mul……"+i);
        int result = i*j;
        System.out.println("add……"+result);
        return result;
    }
}

Main.class

package test;

import com.aop.Calculator;
import com.aop.RealizationCalculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest5 {
    public static void main(String[] args) {
        //创建IOC容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("aop-application.xml");

        //从IOC容器中获取bean的实例
        Calculator calculator = applicationContext.getBean(Calculator.class);
        
        //使用Bean
        int result = calculator.add(2,3);
        System.out.println(result);

    }
}

 

  • 14
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
@Aspect注解Spring框架中用于定义切面的注解。通过在一个类上添加@Aspect注解,该类就成为了一个切面。在该类中,我们可以定义各种各样的通知(Advice),如@Before、@After、@Around等等,来拦截、增强目标方法的执行。 @Aspect注解需要和其他注解配合使用,其中最常用的注解是@Pointcut和@Before/@After/@Around等通知注解。@Pointcut注解用于定义切点,即需要被拦截的目标方法,而@Before/@After/@Around等通知注解则用于定义具体的拦截逻辑。 例如,我们可以在一个类中定义如下的@Aspect切面: ```java @Aspect @Component public class LogAspect { @Pointcut("execution(* com.example.demo.service..*.*(..))") public void serviceMethod() {} @Before("serviceMethod()") public void before(JoinPoint joinPoint) { // 在目标方法执行之前执行的逻辑 ... } @AfterReturning("serviceMethod()") public void afterReturning(JoinPoint joinPoint) { // 在目标方法执行之后执行的逻辑 ... } @AfterThrowing("serviceMethod()") public void afterThrowing(JoinPoint joinPoint) { // 在目标方法抛出异常时执行的逻辑 ... } @Around("serviceMethod()") public Object around(ProceedingJoinPoint pjp) throws Throwable { // 在目标方法执行前后执行的逻辑 ... Object result = pjp.proceed(); ... return result; } } ``` 在上述代码中,我们使用@Pointcut注解定义了一个切点serviceMethod(),该切点匹配所有com.example.demo.service包及其子包中的所有方法。然后我们使用@Before、@AfterReturning、@AfterThrowing和@Around注解定义了各种通知,来实现在目标方法执行前后、抛出异常时执行相关逻辑的功能。最后,我们将该类标注为@Component,使得Spring容器可以自动扫描并加载该切面。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值