Spring的AOP切面编程

简介: Spring的AOP切面编程

语言苍白无力,我们直接代码说话


package com.example.demo.aspect;
import org.springframework.stereotype.Component;
@Component
public class AtithmeticCalulator {
  public int add(int a,int b){
    return a+b;
  }
  public int sub(int a,int b){
    return a-b;
  }
  public int mul(int a,int b){
    return a*b;
  }
  public int div(int a,int b){
    return a/b;
  }
}


这是一个类,以方法add为例,当我们想在每一个方面前面添加一个告诉自己方法名和参数的时候,你会怎么写?


  public int add(int a,int b){
    System.out.println("method mane:add    参数["+a+","+b+"]");
    return a+b;
  }


有没有感觉很麻烦,如果我四个方法都要用,你就要写4遍


这个时候AOP派上用场


package com.example.demo.aspect;  
import java.util.Arrays;  
import java.util.List;  
import org.aspectj.lang.JoinPoint;  
import org.aspectj.lang.annotation.After;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Before;  
import org.springframework.stereotype.Component;  
@Component//将组件加载到ioc容器,必须写,否则加载不到ioc容器  
@Aspect//告诉ioc容器这是一个切面类,里面有切面方法  
public class MyAspect {  
    //切面表达式public int com.example.demo.aspect.AtithmeticCalulator.*(int,int)  
    //包com.example.demo.aspect下的AtithmeticCalulator类所是public ,返回值是int,参数是(int,int)的方法  
    @Before("execution(public int com.example.demo.aspect.AtithmeticCalulator.*(int,int))")
    public void before(JoinPoint joinPoint) {  
        String name=joinPoint.getSignature().getName();  
        List<Object> args=Arrays.asList(joinPoint.getArgs());  
        System.out.println("----the method "+name +" is begin:"+args);  
    }  
    @After("execution(public int com.example.demo.aspect.AtithmeticCalulator.*(int,int))")  
    public void after(JoinPoint joinPoint) {  
        String name=joinPoint.getSignature().getName();  
        List<Object> args=Arrays.asList(joinPoint.getArgs());  
        System.out.println("----the method "+name +" is close:"+args);  
    }  
}  


运行结果所示:


13.png

目录
相关文章
|
6天前
|
运维 Java 程序员
Spring5深入浅出篇:基于注解实现的AOP
# Spring5 AOP 深入理解:注解实现 本文介绍了基于注解的AOP编程步骤,包括原始对象、额外功能、切点和组装切面。步骤1-3旨在构建切面,与传统AOP相似。示例代码展示了如何使用`@Around`定义切面和执行逻辑。配置中,通过`@Aspect`和`@Around`注解定义切点,并在Spring配置中启用AOP自动代理。 进一步讨论了切点复用,避免重复代码以提高代码维护性。通过`@Pointcut`定义通用切点表达式,然后在多个通知中引用。此外,解释了AOP底层实现的两种动态代理方式:JDK动态代理和Cglib字节码增强,默认使用JDK,可通过配置切换到Cglib
|
16小时前
|
XML Java 数据格式
Spring高手之路18——从XML配置角度理解Spring AOP
本文是全面解析面向切面编程的实践指南。通过深入讲解切面、连接点、通知等关键概念,以及通过XML配置实现Spring AOP的步骤。
21 6
Spring高手之路18——从XML配置角度理解Spring AOP
|
6天前
|
XML Java 数据格式
Spring使用AOP 的其他方式
Spring使用AOP 的其他方式
15 2
|
6天前
|
XML Java 数据格式
Spring 项目如何使用AOP
Spring 项目如何使用AOP
19 2
|
10天前
|
XML 监控 安全
18:面向切面编程-Java Spring
18:面向切面编程-Java Spring
27 5
|
12天前
|
Java 开发者 Spring
Spring AOP的切点是通过使用AspectJ的切点表达式语言来定义的。
【5月更文挑战第1天】Spring AOP的切点是通过使用AspectJ的切点表达式语言来定义的。
24 5
|
12天前
|
XML Java 数据格式
Spring AOP
【5月更文挑战第1天】Spring AOP
27 5
|
12天前
|
Java 编译器 开发者
Spring的AOP理解
Spring的AOP理解
|
3月前
|
Java 数据库连接 应用服务中间件
Spring5源码(39)-Aop事物管理简介及编程式事物实现
Spring5源码(39)-Aop事物管理简介及编程式事物实现
26 0
|
4月前
AOP&面向切面编程
AOP&面向切面编程
56 0