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);  
    }  
      
      
  
}  

运行结果所示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CBeann

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值